code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import caffe
from .jpeg_pack import JPEGPack
import numpy
import ast
import threading
import random
class JPEGDataLayer(caffe.Layer):
def setup(self, bottom, top):
self.param_ = eval(self.param_str)
print 'JPEGDataLayer initializing with', self.param_
self.batch_size_ = self.param_['batch_size']
self.jpeg_pack_ = JPEGPack(self.param_['source'])
sample = self.jpeg_pack_.get(self.param_['segment'], 0, self.param_['color'])[0]
assert len(top) > 0, 'Need at least 1 top blob.'
self.mirror_ = self.param_.get('mirror', False)
self.mean_sub_ = self.param_.get('mean_sub', False)
self.mean_sub2_ = self.param_.get('mean_sub2', False)
self.scale_ = self.param_.get('scale', 1.0)
self.scale2_ = self.param_.get('scale2', 1.0)
if 'crop' in self.param_:
self.crop_ = True
self.crop_dim_ = self.param_['crop']
top[0].reshape(self.batch_size_, sample.shape[2], self.crop_dim_[0], self.crop_dim_[1])
else:
self.crop_ = False
top[0].reshape(self.batch_size_, sample.shape[2], sample.shape[0], sample.shape[1])
self.buffer = numpy.zeros(top[0].data.shape)
self.index = 0
if len(top) >= 2:
self.output_label = True;
top[1].reshape(self.batch_size_, 1, 1, 1)
self.label_buffer = numpy.zeros(top[1].data.shape)
if 'source2' in self.param_:
assert len(top) == 3, 'Need 3 top blobs when source2 is set.'
self.output2_ = True
self.jpeg_pack2_ = JPEGPack(self.param_['source2'])
sample2 = self.jpeg_pack2_.get(self.param_['segment2'], 0, self.param_['color2'])[0]
if self.crop_:
assert sample.shape[0] >= sample2.shape[0], 'First output need to be bigger than second one when cropping.'
self.ratio = sample.shape[0]/sample2.shape[0]
assert self.ratio == sample.shape[1]/sample2.shape[1], 'Aspect ratio need to be the same when cropping.'
assert sample.shape[0] % sample2.shape[0] == 0, 'Ratio need to be integeral when cropping.'
assert self.crop_dim_[0] % self.ratio == 0, 'Cropping size need to match when two outputs are given.'
self.crop_dim2_ = (self.crop_dim_[0]/self.ratio, self.crop_dim_[1]/self.ratio)
top[2].reshape(self.batch_size_, sample2.shape[2], self.crop_dim2_[0], self.crop_dim2_[1])
else:
top[2].reshape(self.batch_size_, sample2.shape[2], sample2.shape[0], sample2.shape[1])
self.buffer2 = numpy.zeros(top[2].data.shape)
self.index2 = 0
else:
assert len(top) < 3, 'Need less than 3 top blobs when source2 is not set.'
self.output2_ = False
self.stop_ = False
self.worker = threading.Thread(target=self.fetcher)
self.worker.start()
def reshape(self, bottom, top):
pass
def fetcher(self):
try:
for i in xrange(self.batch_size_):
sample, fname, label = self.jpeg_pack_.get(self.param_['segment'], self.index, self.param_['color'], self.mean_sub_)
if self.crop_:
if self.output2_:
cx = random.randint(0, (sample.shape[0] - self.crop_dim_[0])/self.ratio) * self.ratio
cy = random.randint(0, (sample.shape[1] - self.crop_dim_[1])/self.ratio) * self.ratio
else:
cx = random.randint(0, (sample.shape[0] - self.crop_dim_[0]))
cy = random.randint(0, (sample.shape[1] - self.crop_dim_[1]))
sample = sample[cx:cx+self.crop_dim_[0], cy:cy+self.crop_dim_[1], :]
if self.mirror_:
flag_mirror = random.random() < 0.5
if flag_mirror:
sample = numpy.fliplr(sample)
self.buffer[i,...] = sample.transpose((2,0,1)) * self.scale_
if self.output_label:
self.label_buffer[i,0,0,0] = label
if self.output2_:
sample2, fname, label = self.jpeg_pack2_.get(self.param_['segment2'], self.index, self.param_['color2'], self.mean_sub2_)
if self.crop_:
cx2 = cx / self.ratio
cy2 = cy / self.ratio
sample2 = sample2[cx2:cx2+self.crop_dim2_[0], cy2:cy2+self.crop_dim2_[1]]
if self.mirror_ and flag_mirror:
sample2 = numpy.fliplr(sample2)
self.buffer2[i,...] = sample2.transpose((2,0,1)) * self.scale2_
self.index += 1
except:
self.worker_succeed = False
raise
else:
self.worker_succeed = True
def forward(self, bottom, top):
self.worker.join()
assert self.worker_succeed, 'Prefetching failed.'
top[0].data[...] = self.buffer
if self.output_label:
top[1].data[...] = self.label_buffer
if self.output2_:
top[2].data[...] = self.buffer2
self.worker = threading.Thread(target=self.fetcher)
self.worker.start()
def backward(self, top, propagate_down, bottom):
pass | python/caffe_util/jpeg_data_layer.py | import caffe
from .jpeg_pack import JPEGPack
import numpy
import ast
import threading
import random
class JPEGDataLayer(caffe.Layer):
def setup(self, bottom, top):
self.param_ = eval(self.param_str)
print 'JPEGDataLayer initializing with', self.param_
self.batch_size_ = self.param_['batch_size']
self.jpeg_pack_ = JPEGPack(self.param_['source'])
sample = self.jpeg_pack_.get(self.param_['segment'], 0, self.param_['color'])[0]
assert len(top) > 0, 'Need at least 1 top blob.'
self.mirror_ = self.param_.get('mirror', False)
self.mean_sub_ = self.param_.get('mean_sub', False)
self.mean_sub2_ = self.param_.get('mean_sub2', False)
self.scale_ = self.param_.get('scale', 1.0)
self.scale2_ = self.param_.get('scale2', 1.0)
if 'crop' in self.param_:
self.crop_ = True
self.crop_dim_ = self.param_['crop']
top[0].reshape(self.batch_size_, sample.shape[2], self.crop_dim_[0], self.crop_dim_[1])
else:
self.crop_ = False
top[0].reshape(self.batch_size_, sample.shape[2], sample.shape[0], sample.shape[1])
self.buffer = numpy.zeros(top[0].data.shape)
self.index = 0
if len(top) >= 2:
self.output_label = True;
top[1].reshape(self.batch_size_, 1, 1, 1)
self.label_buffer = numpy.zeros(top[1].data.shape)
if 'source2' in self.param_:
assert len(top) == 3, 'Need 3 top blobs when source2 is set.'
self.output2_ = True
self.jpeg_pack2_ = JPEGPack(self.param_['source2'])
sample2 = self.jpeg_pack2_.get(self.param_['segment2'], 0, self.param_['color2'])[0]
if self.crop_:
assert sample.shape[0] >= sample2.shape[0], 'First output need to be bigger than second one when cropping.'
self.ratio = sample.shape[0]/sample2.shape[0]
assert self.ratio == sample.shape[1]/sample2.shape[1], 'Aspect ratio need to be the same when cropping.'
assert sample.shape[0] % sample2.shape[0] == 0, 'Ratio need to be integeral when cropping.'
assert self.crop_dim_[0] % self.ratio == 0, 'Cropping size need to match when two outputs are given.'
self.crop_dim2_ = (self.crop_dim_[0]/self.ratio, self.crop_dim_[1]/self.ratio)
top[2].reshape(self.batch_size_, sample2.shape[2], self.crop_dim2_[0], self.crop_dim2_[1])
else:
top[2].reshape(self.batch_size_, sample2.shape[2], sample2.shape[0], sample2.shape[1])
self.buffer2 = numpy.zeros(top[2].data.shape)
self.index2 = 0
else:
assert len(top) < 3, 'Need less than 3 top blobs when source2 is not set.'
self.output2_ = False
self.stop_ = False
self.worker = threading.Thread(target=self.fetcher)
self.worker.start()
def reshape(self, bottom, top):
pass
def fetcher(self):
try:
for i in xrange(self.batch_size_):
sample, fname, label = self.jpeg_pack_.get(self.param_['segment'], self.index, self.param_['color'], self.mean_sub_)
if self.crop_:
if self.output2_:
cx = random.randint(0, (sample.shape[0] - self.crop_dim_[0])/self.ratio) * self.ratio
cy = random.randint(0, (sample.shape[1] - self.crop_dim_[1])/self.ratio) * self.ratio
else:
cx = random.randint(0, (sample.shape[0] - self.crop_dim_[0]))
cy = random.randint(0, (sample.shape[1] - self.crop_dim_[1]))
sample = sample[cx:cx+self.crop_dim_[0], cy:cy+self.crop_dim_[1], :]
if self.mirror_:
flag_mirror = random.random() < 0.5
if flag_mirror:
sample = numpy.fliplr(sample)
self.buffer[i,...] = sample.transpose((2,0,1)) * self.scale_
if self.output_label:
self.label_buffer[i,0,0,0] = label
if self.output2_:
sample2, fname, label = self.jpeg_pack2_.get(self.param_['segment2'], self.index, self.param_['color2'], self.mean_sub2_)
if self.crop_:
cx2 = cx / self.ratio
cy2 = cy / self.ratio
sample2 = sample2[cx2:cx2+self.crop_dim2_[0], cy2:cy2+self.crop_dim2_[1]]
if self.mirror_ and flag_mirror:
sample2 = numpy.fliplr(sample2)
self.buffer2[i,...] = sample2.transpose((2,0,1)) * self.scale2_
self.index += 1
except:
self.worker_succeed = False
raise
else:
self.worker_succeed = True
def forward(self, bottom, top):
self.worker.join()
assert self.worker_succeed, 'Prefetching failed.'
top[0].data[...] = self.buffer
if self.output_label:
top[1].data[...] = self.label_buffer
if self.output2_:
top[2].data[...] = self.buffer2
self.worker = threading.Thread(target=self.fetcher)
self.worker.start()
def backward(self, top, propagate_down, bottom):
pass | 0.433022 | 0.340293 |
import matplotlib.pylab as pylab
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pickle
arrays = ['BH', 'BS', 'DR', 'GC', 'PA', 'TB']
type_stack = 'PWS'
cc_stack = 'PWS'
threshold = 0.005
# Read output files
for num, array in enumerate(arrays):
df_temp = pickle.load(open('cc/{}/{}_{}_{}_width_reloc_0.pkl'.format( \
array, array, type_stack, cc_stack), 'rb'))
if (num == 0):
df0 = df_temp
else:
df0 = pd.concat([df0, df_temp], ignore_index=True)
for num, array in enumerate(arrays):
df_temp = pickle.load(open('cc/{}/{}_{}_{}_width_reloc_m1.pkl'.format( \
array, array, type_stack, cc_stack), 'rb'))
if (num == 0):
df1 = df_temp
else:
df1 = pd.concat([df1, df_temp], ignore_index=True)
for num, array in enumerate(arrays):
df_temp = pickle.load(open('cc/{}/{}_{}_{}_width_reloc_p1.pkl'.format( \
array, array, type_stack, cc_stack), 'rb'))
if (num == 0):
df2 = df_temp
else:
df2 = pd.concat([df2, df_temp], ignore_index=True)
params = {'legend.fontsize': 24, \
'xtick.labelsize':24, \
'ytick.labelsize':24}
pylab.rcParams.update(params)
plt.figure(1, figsize=(12, 6))
df = df0.merge(df1, on=['i', 'j', 'latitude', 'longitude', 'distance', \
'ntremor', 'ratioE', 'ratioN', 'maxE', 'maxN'], how='left', indicator=True)
# Drop values for which peak is too small
df.drop(df[(df.maxE < threshold) & (df.maxN < threshold)].index, inplace=True)
df.reset_index(drop=True, inplace=True)
distance = np.zeros(len(df))
time = np.zeros(len(df))
variations = np.zeros(len(df))
for i in range(0, len(df)):
distance[i] = df['distance'][i]
if df['maxE'][i] > df['maxN'][i]:
time[i] = df['time_EW_x'][i]
variations[i] = df['dist_EW_y'][i] - df['dist_EW_x'][i]
else:
time[i] = df['time_NS_x'][i]
variations[i] = df['dist_NS_y'][i] - df['dist_NS_x'][i]
#ax1 = plt.subplot(221)
#plt.plot(time, variations, 'ko')
#plt.xlabel('Time (s)', fontsize=20)
#plt.ylabel('Depth difference (km)', fontsize=20)
#plt.title('Smaller Vp / Vs', fontsize=20)
ax1 = plt.subplot(121)
plt.plot(distance, variations, 'ko')
plt.xlabel('Distance from array (km)', fontsize=20)
plt.ylabel('Depth difference (km)', fontsize=20)
plt.title('Smaller Vp / Vs', fontsize=20)
df = df0.merge(df2, on=['i', 'j', 'latitude', 'longitude', 'distance', \
'ntremor', 'ratioE', 'ratioN', 'maxE', 'maxN'], how='left', indicator=True)
# Drop values for which peak is too small
df.drop(df[(df.maxE < threshold) & (df.maxN < threshold)].index, inplace=True)
df.reset_index(drop=True, inplace=True)
distance = np.zeros(len(df))
time = np.zeros(len(df))
variations = np.zeros(len(df))
for i in range(0, len(df)):
distance[i] = df['distance'][i]
if df['maxE'][i] > df['maxN'][i]:
time[i] = df['time_EW_x'][i]
variations[i] = df['dist_EW_y'][i] - df['dist_EW_x'][i]
else:
time[i] = df['time_NS_x'][i]
variations[i] = df['dist_NS_y'][i] - df['dist_NS_x'][i]
#ax3 = plt.subplot(222)
#plt.plot(time, variations, 'ko')
#plt.xlabel('Time (s)', fontsize=20)
#plt.ylabel('Depth difference (km)', fontsize=20)
#plt.title('Larger Vp / Vs', fontsize=20)
ax2 = plt.subplot(122)
plt.plot(distance, variations, 'ko')
plt.xlabel('Distance from array (km)', fontsize=20)
plt.ylabel('Depth difference (km)', fontsize=20)
plt.title('Larger Vp / Vs', fontsize=20)
plt.tight_layout()
plt.savefig('variations/{}_{}_reloc.eps'.format(type_stack, cc_stack), format='eps')
ax1.clear()
ax2.clear()
#ax3.clear()
#ax4.clear()
plt.close(1) | src/plot_variations.py |
import matplotlib.pylab as pylab
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pickle
arrays = ['BH', 'BS', 'DR', 'GC', 'PA', 'TB']
type_stack = 'PWS'
cc_stack = 'PWS'
threshold = 0.005
# Read output files
for num, array in enumerate(arrays):
df_temp = pickle.load(open('cc/{}/{}_{}_{}_width_reloc_0.pkl'.format( \
array, array, type_stack, cc_stack), 'rb'))
if (num == 0):
df0 = df_temp
else:
df0 = pd.concat([df0, df_temp], ignore_index=True)
for num, array in enumerate(arrays):
df_temp = pickle.load(open('cc/{}/{}_{}_{}_width_reloc_m1.pkl'.format( \
array, array, type_stack, cc_stack), 'rb'))
if (num == 0):
df1 = df_temp
else:
df1 = pd.concat([df1, df_temp], ignore_index=True)
for num, array in enumerate(arrays):
df_temp = pickle.load(open('cc/{}/{}_{}_{}_width_reloc_p1.pkl'.format( \
array, array, type_stack, cc_stack), 'rb'))
if (num == 0):
df2 = df_temp
else:
df2 = pd.concat([df2, df_temp], ignore_index=True)
params = {'legend.fontsize': 24, \
'xtick.labelsize':24, \
'ytick.labelsize':24}
pylab.rcParams.update(params)
plt.figure(1, figsize=(12, 6))
df = df0.merge(df1, on=['i', 'j', 'latitude', 'longitude', 'distance', \
'ntremor', 'ratioE', 'ratioN', 'maxE', 'maxN'], how='left', indicator=True)
# Drop values for which peak is too small
df.drop(df[(df.maxE < threshold) & (df.maxN < threshold)].index, inplace=True)
df.reset_index(drop=True, inplace=True)
distance = np.zeros(len(df))
time = np.zeros(len(df))
variations = np.zeros(len(df))
for i in range(0, len(df)):
distance[i] = df['distance'][i]
if df['maxE'][i] > df['maxN'][i]:
time[i] = df['time_EW_x'][i]
variations[i] = df['dist_EW_y'][i] - df['dist_EW_x'][i]
else:
time[i] = df['time_NS_x'][i]
variations[i] = df['dist_NS_y'][i] - df['dist_NS_x'][i]
#ax1 = plt.subplot(221)
#plt.plot(time, variations, 'ko')
#plt.xlabel('Time (s)', fontsize=20)
#plt.ylabel('Depth difference (km)', fontsize=20)
#plt.title('Smaller Vp / Vs', fontsize=20)
ax1 = plt.subplot(121)
plt.plot(distance, variations, 'ko')
plt.xlabel('Distance from array (km)', fontsize=20)
plt.ylabel('Depth difference (km)', fontsize=20)
plt.title('Smaller Vp / Vs', fontsize=20)
df = df0.merge(df2, on=['i', 'j', 'latitude', 'longitude', 'distance', \
'ntremor', 'ratioE', 'ratioN', 'maxE', 'maxN'], how='left', indicator=True)
# Drop values for which peak is too small
df.drop(df[(df.maxE < threshold) & (df.maxN < threshold)].index, inplace=True)
df.reset_index(drop=True, inplace=True)
distance = np.zeros(len(df))
time = np.zeros(len(df))
variations = np.zeros(len(df))
for i in range(0, len(df)):
distance[i] = df['distance'][i]
if df['maxE'][i] > df['maxN'][i]:
time[i] = df['time_EW_x'][i]
variations[i] = df['dist_EW_y'][i] - df['dist_EW_x'][i]
else:
time[i] = df['time_NS_x'][i]
variations[i] = df['dist_NS_y'][i] - df['dist_NS_x'][i]
#ax3 = plt.subplot(222)
#plt.plot(time, variations, 'ko')
#plt.xlabel('Time (s)', fontsize=20)
#plt.ylabel('Depth difference (km)', fontsize=20)
#plt.title('Larger Vp / Vs', fontsize=20)
ax2 = plt.subplot(122)
plt.plot(distance, variations, 'ko')
plt.xlabel('Distance from array (km)', fontsize=20)
plt.ylabel('Depth difference (km)', fontsize=20)
plt.title('Larger Vp / Vs', fontsize=20)
plt.tight_layout()
plt.savefig('variations/{}_{}_reloc.eps'.format(type_stack, cc_stack), format='eps')
ax1.clear()
ax2.clear()
#ax3.clear()
#ax4.clear()
plt.close(1) | 0.360377 | 0.420421 |
import sys
from datetime import datetime, timezone, timedelta
from oauth2client import client
from googleapiclient import sample_tools
def main(argv):
# Authenticate and construct service.
service, flags = sample_tools.init(
argv, 'calendar', 'v3', __doc__, __file__,
scope='https://www.googleapis.com/auth/calendar.readonly')
# Global Variable Definitions
email = '<EMAIL>' # This should be your gmail address tied to your calendar
domain = (email.split("@",1))[1]
meanSalary = 100000 # Modify this to match your company/team's mean salary
meanSalaryPerHour = round(meanSalary/2080,2)
totalMeetings = 0
totalHours = 0
totalCost = 0
startDays = 30 # Number of days to go back in time to start analyzing - 0 = Today
endDays = 0 # Number of days to go forward in time to start analyzing - 0 = Today
today = datetime.now(timezone.utc).astimezone().replace(microsecond=0)
start = (today - timedelta(startDays)).isoformat()
end = (today + timedelta(endDays)).isoformat()
try:
page_token = None
while True:
# Connect via google API and query all meeting events within start and end dates in global variables
calendar = service.calendars().get(calendarId=email).execute()
events = service.events().list(calendarId=calendar['summary'], pageToken=page_token, showDeleted=False, timeMin=start, timeMax=end, singleEvents=True, orderBy='startTime').execute()
for event in events['items']:
# Cancelled meetings don't show a summary and throw an error, so check that the event has the summary property
if 'summary' in event:
# Timey Wimey stuff - Skip meetings that are full day meetings and don't use proper time format - Typically PTO/Vacation stuff
try:
eventStartObj = datetime.strptime((event['start'].get('dateTime', event['start'].get('date'))), '%Y-%m-%dT%H:%M:%S%z')
eventEndObj = datetime.strptime((event['end'].get('dateTime', event['end'].get('date'))), '%Y-%m-%dT%H:%M:%S%z')
eventDur = round((eventEndObj - eventStartObj).total_seconds()/3600,3)
except:
exit
# Initialize variable to track Company Employees that have Accepted the meeting request for the current meeting event
acceptedAttendees = 0
# Solo event/placeholders in the calendar doesn't have an attendees property, so check for that
if 'attendees' in event:
for i in event['attendees']:
# Iterate the number of Company Employees that have Accepted the meeting request
if i['responseStatus'] == 'accepted':
if '@' + domain in i['email']:
acceptedAttendees+=1
else: exit
else: exit
#Print each event title, its duration in hours, the number of Company Employees that accepted, and calculate the cost of that meeting based on the meanSalaryPerHour global variable
print(event['summary'] + ", " + str(eventDur) + " Hours, " + str(acceptedAttendees) + " " + domain + " Attendees, COST: ${:,.2f}".format(float(acceptedAttendees)*meanSalaryPerHour*float(eventDur)))
# Iterate total number of meetings used to calculate cost
totalMeetings += 1
else:
# Don't track time or cost for solo events
exit
# Calculate Hours and Cost of meetings against global variables
totalHours += (acceptedAttendees * eventDur)
totalCost += (float(acceptedAttendees) * meanSalaryPerHour)
else:
exit
# If you have a shit ton of meetings, the google API paginates the responses. This moves to the next batch of meeting events.
page_token = events.get('nextPageToken')
if not page_token:
break
# Dump the global variables for total time and cost pissed away in meeting events
print ("TOTAL MEETINGS: " + str(totalMeetings) + " TOTAL MEETING HOURS: " + str(round(totalHours,2)) + " TOTAL COST: ${:,.2f}".format(float(totalCost)))
# If your token has expired, it should pop up a browser and ask you to authenticate the app, but just in case throw the exception
except client.AccessTokenRefreshError:
print('The credentials have been revoked or expired, please re-run'
'the application to re-authorize.')
if __name__ == '__main__':
main(sys.argv) | MoneyPit.py | import sys
from datetime import datetime, timezone, timedelta
from oauth2client import client
from googleapiclient import sample_tools
def main(argv):
# Authenticate and construct service.
service, flags = sample_tools.init(
argv, 'calendar', 'v3', __doc__, __file__,
scope='https://www.googleapis.com/auth/calendar.readonly')
# Global Variable Definitions
email = '<EMAIL>' # This should be your gmail address tied to your calendar
domain = (email.split("@",1))[1]
meanSalary = 100000 # Modify this to match your company/team's mean salary
meanSalaryPerHour = round(meanSalary/2080,2)
totalMeetings = 0
totalHours = 0
totalCost = 0
startDays = 30 # Number of days to go back in time to start analyzing - 0 = Today
endDays = 0 # Number of days to go forward in time to start analyzing - 0 = Today
today = datetime.now(timezone.utc).astimezone().replace(microsecond=0)
start = (today - timedelta(startDays)).isoformat()
end = (today + timedelta(endDays)).isoformat()
try:
page_token = None
while True:
# Connect via google API and query all meeting events within start and end dates in global variables
calendar = service.calendars().get(calendarId=email).execute()
events = service.events().list(calendarId=calendar['summary'], pageToken=page_token, showDeleted=False, timeMin=start, timeMax=end, singleEvents=True, orderBy='startTime').execute()
for event in events['items']:
# Cancelled meetings don't show a summary and throw an error, so check that the event has the summary property
if 'summary' in event:
# Timey Wimey stuff - Skip meetings that are full day meetings and don't use proper time format - Typically PTO/Vacation stuff
try:
eventStartObj = datetime.strptime((event['start'].get('dateTime', event['start'].get('date'))), '%Y-%m-%dT%H:%M:%S%z')
eventEndObj = datetime.strptime((event['end'].get('dateTime', event['end'].get('date'))), '%Y-%m-%dT%H:%M:%S%z')
eventDur = round((eventEndObj - eventStartObj).total_seconds()/3600,3)
except:
exit
# Initialize variable to track Company Employees that have Accepted the meeting request for the current meeting event
acceptedAttendees = 0
# Solo event/placeholders in the calendar doesn't have an attendees property, so check for that
if 'attendees' in event:
for i in event['attendees']:
# Iterate the number of Company Employees that have Accepted the meeting request
if i['responseStatus'] == 'accepted':
if '@' + domain in i['email']:
acceptedAttendees+=1
else: exit
else: exit
#Print each event title, its duration in hours, the number of Company Employees that accepted, and calculate the cost of that meeting based on the meanSalaryPerHour global variable
print(event['summary'] + ", " + str(eventDur) + " Hours, " + str(acceptedAttendees) + " " + domain + " Attendees, COST: ${:,.2f}".format(float(acceptedAttendees)*meanSalaryPerHour*float(eventDur)))
# Iterate total number of meetings used to calculate cost
totalMeetings += 1
else:
# Don't track time or cost for solo events
exit
# Calculate Hours and Cost of meetings against global variables
totalHours += (acceptedAttendees * eventDur)
totalCost += (float(acceptedAttendees) * meanSalaryPerHour)
else:
exit
# If you have a shit ton of meetings, the google API paginates the responses. This moves to the next batch of meeting events.
page_token = events.get('nextPageToken')
if not page_token:
break
# Dump the global variables for total time and cost pissed away in meeting events
print ("TOTAL MEETINGS: " + str(totalMeetings) + " TOTAL MEETING HOURS: " + str(round(totalHours,2)) + " TOTAL COST: ${:,.2f}".format(float(totalCost)))
# If your token has expired, it should pop up a browser and ask you to authenticate the app, but just in case throw the exception
except client.AccessTokenRefreshError:
print('The credentials have been revoked or expired, please re-run'
'the application to re-authorize.')
if __name__ == '__main__':
main(sys.argv) | 0.267408 | 0.207375 |
import matplotlib.pyplot as plt
from optimism.JaxConfig import *
from optimism.contact.SmoothMinMax import *
from optimism.test.TestFixture import *
class TestSmoothMinMax(TestFixture):
def test_max_x_zero(self):
tol = 0.2
eps = 1e-15
tolm = tol*(1.-eps)
self.assertEqual(0.0, zmax(-tol, tol))
self.assertNear(0.0, zmax(-tolm, tol), 15)
self.assertEqual(tol, zmax(tol, tol))
self.assertNear(tolm, zmax(tolm, tol), 15)
self.assertEqual(1.1*tol, zmax(1.1*tol, tol))
zmax_grad = grad( partial(zmax, eps=tol) )
self.assertNear(zmax_grad(-eps), zmax_grad(eps), 14)
self.assertNear(zmax_grad(-tol-eps), zmax_grad(-tol+eps), 14)
self.assertNear(zmax_grad(tol-eps), zmax_grad(tol+eps), 14)
def test_min(self):
tol = 0.2
eps = 1e-2
tolm = tol*(1.-eps)
x = 0.41
self.assertEqual(x, min(x, x+tol, tol))
self.assertEqual(x, min(x, x+1.1*tol, tol))
self.assertEqual(x-tol, min(x, x-tol, tol))
self.assertEqual(x-1.1*tol, min(x, x-1.1*tol, tol))
self.assertEqual(x, min(x+tol, x, tol))
self.assertEqual(x, min(x+1.1*tol, x, tol))
self.assertEqual(x-tol, min(x-tol, x, tol))
self.assertEqual(x-1.1*tol, min(x-1.1*tol, x, tol))
minVal = min(x, x, tol)
self.assertTrue(minVal > x - tol)
self.assertTrue(minVal < x)
minVal = min(x, x-tolm, tol)
self.assertTrue(minVal > x - tol)
self.assertTrue(minVal < x)
minVal = min(x, x+tolm, tol)
self.assertTrue(minVal > x - tol)
self.assertTrue(minVal < x)
def test_inf_min(self):
eps = 1e-5
self.assertEqual(0.0, min(0.0, np.inf, eps))
self.assertEqual(0.0, min(np.inf, 0.0, eps))
self.assertEqual(np.inf, min(np.inf, np.inf, eps))
self.assertEqual(-np.inf, min(np.inf, -np.inf, eps))
self.assertEqual(-np.inf, min(-np.inf, np.inf, eps))
self.assertEqual(-np.inf, min(-np.inf, -np.inf, eps))
def test_inf_grad_min(self):
eps = 1e-5
grad_min = grad(min, (0,1))
self.assertArrayEqual(np.array([1.0, 0.0]), grad_min(0.0, np.inf, eps))
self.assertArrayEqual(np.array([0.0, 1.0]), grad_min(np.inf, 0.0, eps))
self.assertArrayEqual(np.array([1.0, 0.0]), grad_min(np.inf, np.inf, eps))
self.assertArrayEqual(np.array([0.0, 1.0]), grad_min(np.inf, -np.inf, eps))
self.assertArrayEqual(np.array([1.0, 0.0]), grad_min(-np.inf, np.inf, eps))
self.assertArrayEqual(np.array([1.0, 0.0]), grad_min(-np.inf, -np.inf, eps))
if __name__ == '__main__':
unittest.main() | optimism/contact/test/testSmoothMinMax.py | import matplotlib.pyplot as plt
from optimism.JaxConfig import *
from optimism.contact.SmoothMinMax import *
from optimism.test.TestFixture import *
class TestSmoothMinMax(TestFixture):
def test_max_x_zero(self):
tol = 0.2
eps = 1e-15
tolm = tol*(1.-eps)
self.assertEqual(0.0, zmax(-tol, tol))
self.assertNear(0.0, zmax(-tolm, tol), 15)
self.assertEqual(tol, zmax(tol, tol))
self.assertNear(tolm, zmax(tolm, tol), 15)
self.assertEqual(1.1*tol, zmax(1.1*tol, tol))
zmax_grad = grad( partial(zmax, eps=tol) )
self.assertNear(zmax_grad(-eps), zmax_grad(eps), 14)
self.assertNear(zmax_grad(-tol-eps), zmax_grad(-tol+eps), 14)
self.assertNear(zmax_grad(tol-eps), zmax_grad(tol+eps), 14)
def test_min(self):
tol = 0.2
eps = 1e-2
tolm = tol*(1.-eps)
x = 0.41
self.assertEqual(x, min(x, x+tol, tol))
self.assertEqual(x, min(x, x+1.1*tol, tol))
self.assertEqual(x-tol, min(x, x-tol, tol))
self.assertEqual(x-1.1*tol, min(x, x-1.1*tol, tol))
self.assertEqual(x, min(x+tol, x, tol))
self.assertEqual(x, min(x+1.1*tol, x, tol))
self.assertEqual(x-tol, min(x-tol, x, tol))
self.assertEqual(x-1.1*tol, min(x-1.1*tol, x, tol))
minVal = min(x, x, tol)
self.assertTrue(minVal > x - tol)
self.assertTrue(minVal < x)
minVal = min(x, x-tolm, tol)
self.assertTrue(minVal > x - tol)
self.assertTrue(minVal < x)
minVal = min(x, x+tolm, tol)
self.assertTrue(minVal > x - tol)
self.assertTrue(minVal < x)
def test_inf_min(self):
eps = 1e-5
self.assertEqual(0.0, min(0.0, np.inf, eps))
self.assertEqual(0.0, min(np.inf, 0.0, eps))
self.assertEqual(np.inf, min(np.inf, np.inf, eps))
self.assertEqual(-np.inf, min(np.inf, -np.inf, eps))
self.assertEqual(-np.inf, min(-np.inf, np.inf, eps))
self.assertEqual(-np.inf, min(-np.inf, -np.inf, eps))
def test_inf_grad_min(self):
eps = 1e-5
grad_min = grad(min, (0,1))
self.assertArrayEqual(np.array([1.0, 0.0]), grad_min(0.0, np.inf, eps))
self.assertArrayEqual(np.array([0.0, 1.0]), grad_min(np.inf, 0.0, eps))
self.assertArrayEqual(np.array([1.0, 0.0]), grad_min(np.inf, np.inf, eps))
self.assertArrayEqual(np.array([0.0, 1.0]), grad_min(np.inf, -np.inf, eps))
self.assertArrayEqual(np.array([1.0, 0.0]), grad_min(-np.inf, np.inf, eps))
self.assertArrayEqual(np.array([1.0, 0.0]), grad_min(-np.inf, -np.inf, eps))
if __name__ == '__main__':
unittest.main() | 0.47244 | 0.7413 |
import sys
from xml.etree.ElementTree import parse
if sys.version_info.major > 2:
from urllib.request import urlopen
else:
from urllib import urlopen
import datetime
class Base:
def __init__(self, url):
self.rss = ''
self.fecha = ''
self.__url = url
self.__fecha_de_actualizacion = ''
self.__localidad = ''
self.__provincia = ''
self.precipitacion = []
self.cota_nieve = []
self.estado_cielo = []
self.viento = []
self.racha = []
self.temperatura_maxima = 0
self.temperatura_minima = 0
self.temperatura_horas = []
self.sensacion_termica_maxima = 0
self.sensacion_termica_minima = 0
self.sensacion_termica = []
self.humedad_maxima = 0
self.humedad_minima = 0
self.humedad = []
self.uv_max = 0
self.__load_xml()
def __load_xml(self):
self.rss = parse(urlopen(self.__url)).getroot()
self.__load_datos_base()
def __load_datos_base(self):
self.__fecha_de_actualizacion = self.rss.find('elaborado').text.encode('UTF-8')
self.__localidad = self.rss.find('nombre').text.encode('UTF-8')
self.__provincia = self.rss.find('provincia').text.encode('UTF-8')
'''Interfaz publica'''
def get_fecha_actualizacion(self):
return self.__fecha_de_actualizacion
def get_localidad(self):
return self.__localidad
def get_provincia(self):
return self.__provincia
def get_precipitacion(self):
return self.precipitacion
def get_cota_nieve(self):
return self.cota_nieve
def get_estado_cielo(self):
return self.estado_cielo
def get_viento(self):
return self.viento
def get_racha(self):
return self.racha
def get_temperatura_maxima(self):
return self.temperatura_maxima
def get_temperatura_minima(self):
return self.temperatura_minima
def get_temperatura_horas(self):
return self.temperatura_horas
def get_sensacion_termica_maxima(self):
return self.sensacion_termica_maxima
def get_sensacion_termica_minima(self):
return self.sensacion_termica_minima
def get_sensacion_termica(self):
return self.sensacion_termica
def get_humedad_maxima(self):
return self.humedad_maxima
def get_humedad_minima(self):
return self.humedad_minima
def get_humedad(self):
return self.humedad
def get_uv_max(self):
return self.uv_max
class Localidad(Base):
'''Fecha en formato dd/mm/AAAA'''
def __init__(self, codigo_postal, fecha):
url = 'http://www.aemet.es/xml/municipios/localidad_' + codigo_postal + '.xml'
Base.__init__(self, url)
self.fecha = datetime.datetime.strptime(fecha, '%d/%m/%Y').strftime('%Y-%m-%d')
self.__load_datos(self.fecha)
'''Carga de los datos del XML para el dia seleccionado'''
def __load_datos(self, fecha):
nodo = self.rss.find("prediccion/dia[@fecha='" + fecha + "']")
'''Probabilidad de precipitacion'''
for elem in nodo.findall('prob_precipitacion'):
self.precipitacion.append([elem.get('periodo'), elem.text])
'''Cota de nieve'''
for elem in nodo.findall('cota_nieve_prov'):
self.cota_nieve.append([elem.get('periodo'), elem.text])
'''Estado'''
for elem in nodo.findall('estado_cielo'):
self.estado_cielo.append([elem.get('periodo'), elem.get('descripcion')])
'''Viento'''
for elem in nodo.findall('viento'):
self.viento.append([elem.get('periodo'), elem.find('direccion').text, elem.find('velocidad').text])
'''Racha maxima'''
for elem in nodo.findall('racha_max'):
self.racha.append([elem.get('periodo'), elem.text])
'''Temperaturas'''
self.temperatura_maxima = nodo.find('temperatura/maxima').text
self.temperatura_minima = nodo.find('temperatura/minima').text
for elem in nodo.findall('temperatura/dato'):
self.temperatura_horas.append([elem.get('hora'), elem.text])
'''Sensacion termica'''
self.sensacion_termica_maxima = nodo.find('sens_termica/maxima').text
self.sensacion_termica_minima = nodo.find('sens_termica/minima').text
for elem in nodo.findall('sens_termica/dato'):
self.sensacion_termica.append([elem.get('hora'), elem.text])
'''Humedad'''
self.humedad_maxima = nodo.find('humedad_relativa/maxima').text
self.humedad_minima = nodo.find('humedad_relativa/minima').text
for elem in nodo.findall('humedad_relativa/dato'):
self.humedad.append([elem.get('hora'), elem.text])
'''U.V. Maximo'''
self.uv_max = nodo.find('uv_max').text | src/Aemet.py | import sys
from xml.etree.ElementTree import parse
if sys.version_info.major > 2:
from urllib.request import urlopen
else:
from urllib import urlopen
import datetime
class Base:
def __init__(self, url):
self.rss = ''
self.fecha = ''
self.__url = url
self.__fecha_de_actualizacion = ''
self.__localidad = ''
self.__provincia = ''
self.precipitacion = []
self.cota_nieve = []
self.estado_cielo = []
self.viento = []
self.racha = []
self.temperatura_maxima = 0
self.temperatura_minima = 0
self.temperatura_horas = []
self.sensacion_termica_maxima = 0
self.sensacion_termica_minima = 0
self.sensacion_termica = []
self.humedad_maxima = 0
self.humedad_minima = 0
self.humedad = []
self.uv_max = 0
self.__load_xml()
def __load_xml(self):
self.rss = parse(urlopen(self.__url)).getroot()
self.__load_datos_base()
def __load_datos_base(self):
self.__fecha_de_actualizacion = self.rss.find('elaborado').text.encode('UTF-8')
self.__localidad = self.rss.find('nombre').text.encode('UTF-8')
self.__provincia = self.rss.find('provincia').text.encode('UTF-8')
'''Interfaz publica'''
def get_fecha_actualizacion(self):
return self.__fecha_de_actualizacion
def get_localidad(self):
return self.__localidad
def get_provincia(self):
return self.__provincia
def get_precipitacion(self):
return self.precipitacion
def get_cota_nieve(self):
return self.cota_nieve
def get_estado_cielo(self):
return self.estado_cielo
def get_viento(self):
return self.viento
def get_racha(self):
return self.racha
def get_temperatura_maxima(self):
return self.temperatura_maxima
def get_temperatura_minima(self):
return self.temperatura_minima
def get_temperatura_horas(self):
return self.temperatura_horas
def get_sensacion_termica_maxima(self):
return self.sensacion_termica_maxima
def get_sensacion_termica_minima(self):
return self.sensacion_termica_minima
def get_sensacion_termica(self):
return self.sensacion_termica
def get_humedad_maxima(self):
return self.humedad_maxima
def get_humedad_minima(self):
return self.humedad_minima
def get_humedad(self):
return self.humedad
def get_uv_max(self):
return self.uv_max
class Localidad(Base):
'''Fecha en formato dd/mm/AAAA'''
def __init__(self, codigo_postal, fecha):
url = 'http://www.aemet.es/xml/municipios/localidad_' + codigo_postal + '.xml'
Base.__init__(self, url)
self.fecha = datetime.datetime.strptime(fecha, '%d/%m/%Y').strftime('%Y-%m-%d')
self.__load_datos(self.fecha)
'''Carga de los datos del XML para el dia seleccionado'''
def __load_datos(self, fecha):
nodo = self.rss.find("prediccion/dia[@fecha='" + fecha + "']")
'''Probabilidad de precipitacion'''
for elem in nodo.findall('prob_precipitacion'):
self.precipitacion.append([elem.get('periodo'), elem.text])
'''Cota de nieve'''
for elem in nodo.findall('cota_nieve_prov'):
self.cota_nieve.append([elem.get('periodo'), elem.text])
'''Estado'''
for elem in nodo.findall('estado_cielo'):
self.estado_cielo.append([elem.get('periodo'), elem.get('descripcion')])
'''Viento'''
for elem in nodo.findall('viento'):
self.viento.append([elem.get('periodo'), elem.find('direccion').text, elem.find('velocidad').text])
'''Racha maxima'''
for elem in nodo.findall('racha_max'):
self.racha.append([elem.get('periodo'), elem.text])
'''Temperaturas'''
self.temperatura_maxima = nodo.find('temperatura/maxima').text
self.temperatura_minima = nodo.find('temperatura/minima').text
for elem in nodo.findall('temperatura/dato'):
self.temperatura_horas.append([elem.get('hora'), elem.text])
'''Sensacion termica'''
self.sensacion_termica_maxima = nodo.find('sens_termica/maxima').text
self.sensacion_termica_minima = nodo.find('sens_termica/minima').text
for elem in nodo.findall('sens_termica/dato'):
self.sensacion_termica.append([elem.get('hora'), elem.text])
'''Humedad'''
self.humedad_maxima = nodo.find('humedad_relativa/maxima').text
self.humedad_minima = nodo.find('humedad_relativa/minima').text
for elem in nodo.findall('humedad_relativa/dato'):
self.humedad.append([elem.get('hora'), elem.text])
'''U.V. Maximo'''
self.uv_max = nodo.find('uv_max').text | 0.107274 | 0.130313 |
import argparse
import tokenize
import re
import typing
import pkgutil
import io
from . import gatekeepers
from . import providers
class Obfuscator:
def obfuscate(
self, source: typing.IO, output: typing.IO, provider: providers.Provider
):
output_tokens = []
gatekeeper = gatekeepers.SafeGatekeeper()
offset = 0
encoding = None
for token in tokenize.tokenize(source.readline):
if token.type == tokenize.ENCODING:
encoding = token.string
"""
if token.type == tokenize.NAME and token.string[0].lower() == "f":
inner_source = io.StringIO()
self.obfuscate()
"""
if gatekeeper.read(token):
meme = provider.meme(token.string)
sub_offset = len(meme) - len(token.string)
output_tokens.append(
(
tokenize.NAME,
meme,
(token.start[0], token.start[1] + offset),
(token.end[0], token.end[1] + offset + sub_offset),
token.line,
)
)
offset += sub_offset
else:
output_tokens.append(
(
token.type,
token.string,
(token.start[0], token.start[1] + offset),
(token.end[0], token.end[1] + offset),
token.line,
)
)
if token.type == tokenize.NEWLINE:
offset = 0
output.write(tokenize.untokenize(output_tokens).decode(encoding))
def main():
parser = argparse.ArgumentParser(
description="Obfuscates variables in collaboration with MIT."
)
parser.add_argument(
"input_file", type=argparse.FileType("rb"), help="the Python file to obfuscate"
)
parser.add_argument(
"-o",
"--output-file",
type=argparse.FileType("w"),
required=False,
help="the destination file",
)
parser.add_argument(
"--random",
action="store_true",
required=False,
help="makes the obfuscation process non deterministic",
)
parser.add_argument(
"--sequential",
"--seq",
action="store_true",
required=False,
help="ensures that all memes in the dictionary are used before recycling names",
)
parser.add_argument(
"--memes",
required=False,
help="custom dictionary file for retrieving replacement names in obfuscation",
)
args = vars(parser.parse_args())
input_file = args.get("input_file")
output_file = args.get("o") or open(
re.sub(r"\.py$", ".sutd.py", input_file.name), "w"
)
try:
if args.get("memes") is None:
raise FileNotFoundError
builtin_dictionary_file = pkgutil.get_data(
"sutdobfs", "memes/" + args.get("memes")
)
dictionary_file = io.StringIO(builtin_dictionary_file.decode("utf-8"))
except FileNotFoundError:
try:
if args.get("memes") is None:
raise FileNotFoundError
user_supplied_dictionary_file = open(args.get("memes"))
dictionary_file = user_supplied_dictionary_file
except FileNotFoundError:
# use default memes.txt
dictionary_file = io.StringIO(
pkgutil.get_data("sutdobfs", "memes/memes.txt").decode("utf-8")
)
memes = [
line.strip()
for line in dictionary_file.readlines()
if str.isidentifier(line.strip())
]
if args.get("random") and args.get("sequential"):
provider = providers.RandomSequentialProvider(memes)
elif args.get("random"):
provider = providers.RandomConsistentProvider(memes)
elif args.get("sequential"):
provider = providers.SequentialProvider(memes)
else:
provider = providers.ConsistentProvider(memes)
obfs = Obfuscator()
obfs.obfuscate(input_file, output_file, provider)
input_file.close()
output_file.close()
return 0
if __name__ == "__main__":
code = main()
exit(code) | sutdobfs/__main__.py | import argparse
import tokenize
import re
import typing
import pkgutil
import io
from . import gatekeepers
from . import providers
class Obfuscator:
def obfuscate(
self, source: typing.IO, output: typing.IO, provider: providers.Provider
):
output_tokens = []
gatekeeper = gatekeepers.SafeGatekeeper()
offset = 0
encoding = None
for token in tokenize.tokenize(source.readline):
if token.type == tokenize.ENCODING:
encoding = token.string
"""
if token.type == tokenize.NAME and token.string[0].lower() == "f":
inner_source = io.StringIO()
self.obfuscate()
"""
if gatekeeper.read(token):
meme = provider.meme(token.string)
sub_offset = len(meme) - len(token.string)
output_tokens.append(
(
tokenize.NAME,
meme,
(token.start[0], token.start[1] + offset),
(token.end[0], token.end[1] + offset + sub_offset),
token.line,
)
)
offset += sub_offset
else:
output_tokens.append(
(
token.type,
token.string,
(token.start[0], token.start[1] + offset),
(token.end[0], token.end[1] + offset),
token.line,
)
)
if token.type == tokenize.NEWLINE:
offset = 0
output.write(tokenize.untokenize(output_tokens).decode(encoding))
def main():
parser = argparse.ArgumentParser(
description="Obfuscates variables in collaboration with MIT."
)
parser.add_argument(
"input_file", type=argparse.FileType("rb"), help="the Python file to obfuscate"
)
parser.add_argument(
"-o",
"--output-file",
type=argparse.FileType("w"),
required=False,
help="the destination file",
)
parser.add_argument(
"--random",
action="store_true",
required=False,
help="makes the obfuscation process non deterministic",
)
parser.add_argument(
"--sequential",
"--seq",
action="store_true",
required=False,
help="ensures that all memes in the dictionary are used before recycling names",
)
parser.add_argument(
"--memes",
required=False,
help="custom dictionary file for retrieving replacement names in obfuscation",
)
args = vars(parser.parse_args())
input_file = args.get("input_file")
output_file = args.get("o") or open(
re.sub(r"\.py$", ".sutd.py", input_file.name), "w"
)
try:
if args.get("memes") is None:
raise FileNotFoundError
builtin_dictionary_file = pkgutil.get_data(
"sutdobfs", "memes/" + args.get("memes")
)
dictionary_file = io.StringIO(builtin_dictionary_file.decode("utf-8"))
except FileNotFoundError:
try:
if args.get("memes") is None:
raise FileNotFoundError
user_supplied_dictionary_file = open(args.get("memes"))
dictionary_file = user_supplied_dictionary_file
except FileNotFoundError:
# use default memes.txt
dictionary_file = io.StringIO(
pkgutil.get_data("sutdobfs", "memes/memes.txt").decode("utf-8")
)
memes = [
line.strip()
for line in dictionary_file.readlines()
if str.isidentifier(line.strip())
]
if args.get("random") and args.get("sequential"):
provider = providers.RandomSequentialProvider(memes)
elif args.get("random"):
provider = providers.RandomConsistentProvider(memes)
elif args.get("sequential"):
provider = providers.SequentialProvider(memes)
else:
provider = providers.ConsistentProvider(memes)
obfs = Obfuscator()
obfs.obfuscate(input_file, output_file, provider)
input_file.close()
output_file.close()
return 0
if __name__ == "__main__":
code = main()
exit(code) | 0.500977 | 0.233379 |
from datetime import datetime, timezone
from unittest.mock import MagicMock
import pytest
from source_dcl_logistics.models.order import Order
from source_dcl_logistics.source import Orders
@pytest.fixture
def patch_base_class(mocker):
# Mock abstract methods to enable instantiating abstract class
mocker.patch.object(Orders, "path", "v0/example_endpoint")
mocker.patch.object(Orders, "primary_key", "test_primary_key")
mocker.patch.object(Orders, "__abstractmethods__", set())
def test_request_params(patch_base_class):
stream = Orders()
inputs = {"stream_slice": None, "stream_state": None, "next_page_token": {"page": 1}}
expected_params = {"extended_date": True, "page": 1, "page_size": 100}
assert stream.request_params(**inputs) == expected_params
def test_parse_response(patch_base_class):
fake_date_pdt_str = "2014-11-25T09:01:28-08:00"
fake_date = datetime.strptime(fake_date_pdt_str, "%Y-%m-%dT%H:%M:%S%z")
stream = Orders()
fake_order = Order(
account_number="FAKE",
order_number="FAKE",
item_number="FAKE",
serial_number="FAKE",
updated_at=fake_date.astimezone(timezone.utc),
)
fake_order_json = {
"account_number": fake_order.account_number,
"order_number": fake_order.order_number,
"shipments": [
{
"shipping_address": {},
"packages": [
{
"shipped_items": [
{
"item_number": fake_order.item_number,
"quantity": fake_order.quantity,
"serial_numbers": [fake_order.serial_number],
}
]
}
],
}
],
"modified_at": fake_date_pdt_str,
}
fake_json_response = {"orders": [fake_order_json]}
inputs = {"response": MagicMock(json=MagicMock(return_value=fake_json_response))}
assert next(stream.parse_response(**inputs)) == fake_order.__dict__
def test_has_more_pages(patch_base_class):
stream = Orders()
fake_json_response = {"orders": None}
inputs = {"response": MagicMock(json=MagicMock(return_value=fake_json_response))}
list(stream.parse_response(**inputs))
assert not stream.has_more_pages | airbyte-integrations/connectors/source-dcl-logistics/unit_tests/test_orders_stream.py |
from datetime import datetime, timezone
from unittest.mock import MagicMock
import pytest
from source_dcl_logistics.models.order import Order
from source_dcl_logistics.source import Orders
@pytest.fixture
def patch_base_class(mocker):
# Mock abstract methods to enable instantiating abstract class
mocker.patch.object(Orders, "path", "v0/example_endpoint")
mocker.patch.object(Orders, "primary_key", "test_primary_key")
mocker.patch.object(Orders, "__abstractmethods__", set())
def test_request_params(patch_base_class):
stream = Orders()
inputs = {"stream_slice": None, "stream_state": None, "next_page_token": {"page": 1}}
expected_params = {"extended_date": True, "page": 1, "page_size": 100}
assert stream.request_params(**inputs) == expected_params
def test_parse_response(patch_base_class):
fake_date_pdt_str = "2014-11-25T09:01:28-08:00"
fake_date = datetime.strptime(fake_date_pdt_str, "%Y-%m-%dT%H:%M:%S%z")
stream = Orders()
fake_order = Order(
account_number="FAKE",
order_number="FAKE",
item_number="FAKE",
serial_number="FAKE",
updated_at=fake_date.astimezone(timezone.utc),
)
fake_order_json = {
"account_number": fake_order.account_number,
"order_number": fake_order.order_number,
"shipments": [
{
"shipping_address": {},
"packages": [
{
"shipped_items": [
{
"item_number": fake_order.item_number,
"quantity": fake_order.quantity,
"serial_numbers": [fake_order.serial_number],
}
]
}
],
}
],
"modified_at": fake_date_pdt_str,
}
fake_json_response = {"orders": [fake_order_json]}
inputs = {"response": MagicMock(json=MagicMock(return_value=fake_json_response))}
assert next(stream.parse_response(**inputs)) == fake_order.__dict__
def test_has_more_pages(patch_base_class):
stream = Orders()
fake_json_response = {"orders": None}
inputs = {"response": MagicMock(json=MagicMock(return_value=fake_json_response))}
list(stream.parse_response(**inputs))
assert not stream.has_more_pages | 0.761716 | 0.296973 |
from django.http import HttpResponse
from django.views.generic import View
import feedgen.feed
import html
import json
import re
import requests
import urllib
from .. import services
class PChomeLightNovelView(View):
def get(self, *args, **kwargs):
url = 'https://ecapi.pchome.com.tw/cdn/ecshop/prodapi/v2/newarrival/DJAZ/prod&offset=1&limit=20&fields=Id,Nick,Pic,Price,Discount,isSpec,Name,isCarrier,isSnapUp,isBigCart&_callback=jsonp_prodlist?_callback=jsonp_prodlist'
title = 'PChome 輕小說'
feed = feedgen.feed.FeedGenerator()
feed.author({'name': 'Feed Generator'})
feed.id(url)
feed.link(href=url, rel='alternate')
feed.title(title)
try:
s = services.RequestsService().process()
r = s.get(url)
body = re.match(r'^[^\[]*(\[.*\])[^\[]*$', r.text).group(1)
items = json.loads(body)
except:
items = []
for item in items:
content = '{}<br/><img alt="{}" src="https://cs-a.ecimg.tw{}"/>'.format(
html.escape(item['Nick']),
html.escape(item['Nick']),
html.escape(item['Pic']['B']),
)
book_title = item['Nick']
book_url = 'https://24h.pchome.com.tw/books/prod/{}'.format(
urllib.parse.quote_plus(item['Id'])
)
entry = feed.add_entry()
entry.content(content, type='xhtml')
entry.id(book_url)
entry.title(book_title)
entry.link(href=book_url)
res = HttpResponse(feed.atom_str(), content_type='application/atom+xml; charset=utf-8')
res['Cache-Control'] = 'max-age=300,public'
return res
class PChomeView(View):
def get(self, *args, **kwargs):
keyword = kwargs['keyword']
url = 'https://ecshweb.pchome.com.tw/search/v3.3/all/results?q={}&page=1&sort=new/dc'.format(urllib.parse.quote_plus(keyword))
title = 'PChome 搜尋 - {}'.format(keyword)
feed = feedgen.feed.FeedGenerator()
feed.author({'name': 'Feed Generator'})
feed.id(url)
feed.link(href=url, rel='alternate')
feed.title(title)
try:
s = services.RequestsService().process()
r = s.get(url)
body = json.loads(r.text)
except:
body = {'prods': []}
for item in body['prods']:
# Product name & description
item_author = self.str_clean(item['author'])
item_desc = self.str_clean(item['describe'])
item_name = self.str_clean(item['name'])
item_origin_price = item['originPrice']
item_price = item['price']
item_title = '(${}/${}) {}'.format(item_origin_price, item_price, item_name)
# URL
if item['cateId'][0] == 'D':
item_url = 'https://24h.pchome.com.tw/prod/' + item['Id']
else:
item_url = 'https://mall.pchome.com.tw/prod/' + item['Id']
img_url = 'https://cs-a.ecimg.tw%s' % (item['picB'])
content = '{}<br/><img alt="{}" src="{}"/>'.format(
html.escape(item_desc), html.escape(item_name), html.escape(img_url)
)
entry = feed.add_entry()
entry.author({'name': item_author})
entry.content(content, type='xhtml')
entry.id(item_url)
entry.link(href=item_url)
entry.title(item_title)
res = HttpResponse(feed.atom_str(), content_type='application/atom+xml; charset=utf-8')
res['Cache-Control'] = 'max-age=300,public'
return res
def str_clean(self, s):
return re.sub(r'[\x00-\x09]', ' ', s) | general/views/pchome.py | from django.http import HttpResponse
from django.views.generic import View
import feedgen.feed
import html
import json
import re
import requests
import urllib
from .. import services
class PChomeLightNovelView(View):
def get(self, *args, **kwargs):
url = 'https://ecapi.pchome.com.tw/cdn/ecshop/prodapi/v2/newarrival/DJAZ/prod&offset=1&limit=20&fields=Id,Nick,Pic,Price,Discount,isSpec,Name,isCarrier,isSnapUp,isBigCart&_callback=jsonp_prodlist?_callback=jsonp_prodlist'
title = 'PChome 輕小說'
feed = feedgen.feed.FeedGenerator()
feed.author({'name': 'Feed Generator'})
feed.id(url)
feed.link(href=url, rel='alternate')
feed.title(title)
try:
s = services.RequestsService().process()
r = s.get(url)
body = re.match(r'^[^\[]*(\[.*\])[^\[]*$', r.text).group(1)
items = json.loads(body)
except:
items = []
for item in items:
content = '{}<br/><img alt="{}" src="https://cs-a.ecimg.tw{}"/>'.format(
html.escape(item['Nick']),
html.escape(item['Nick']),
html.escape(item['Pic']['B']),
)
book_title = item['Nick']
book_url = 'https://24h.pchome.com.tw/books/prod/{}'.format(
urllib.parse.quote_plus(item['Id'])
)
entry = feed.add_entry()
entry.content(content, type='xhtml')
entry.id(book_url)
entry.title(book_title)
entry.link(href=book_url)
res = HttpResponse(feed.atom_str(), content_type='application/atom+xml; charset=utf-8')
res['Cache-Control'] = 'max-age=300,public'
return res
class PChomeView(View):
def get(self, *args, **kwargs):
keyword = kwargs['keyword']
url = 'https://ecshweb.pchome.com.tw/search/v3.3/all/results?q={}&page=1&sort=new/dc'.format(urllib.parse.quote_plus(keyword))
title = 'PChome 搜尋 - {}'.format(keyword)
feed = feedgen.feed.FeedGenerator()
feed.author({'name': 'Feed Generator'})
feed.id(url)
feed.link(href=url, rel='alternate')
feed.title(title)
try:
s = services.RequestsService().process()
r = s.get(url)
body = json.loads(r.text)
except:
body = {'prods': []}
for item in body['prods']:
# Product name & description
item_author = self.str_clean(item['author'])
item_desc = self.str_clean(item['describe'])
item_name = self.str_clean(item['name'])
item_origin_price = item['originPrice']
item_price = item['price']
item_title = '(${}/${}) {}'.format(item_origin_price, item_price, item_name)
# URL
if item['cateId'][0] == 'D':
item_url = 'https://24h.pchome.com.tw/prod/' + item['Id']
else:
item_url = 'https://mall.pchome.com.tw/prod/' + item['Id']
img_url = 'https://cs-a.ecimg.tw%s' % (item['picB'])
content = '{}<br/><img alt="{}" src="{}"/>'.format(
html.escape(item_desc), html.escape(item_name), html.escape(img_url)
)
entry = feed.add_entry()
entry.author({'name': item_author})
entry.content(content, type='xhtml')
entry.id(item_url)
entry.link(href=item_url)
entry.title(item_title)
res = HttpResponse(feed.atom_str(), content_type='application/atom+xml; charset=utf-8')
res['Cache-Control'] = 'max-age=300,public'
return res
def str_clean(self, s):
return re.sub(r'[\x00-\x09]', ' ', s) | 0.336549 | 0.076961 |
from __future__ import division,with_statement
from nose.tools import assert_almost_equal
def test_gal():
"""Cross-check Gal <-> Supergal <-> FK5 coordinate conversions.
Implicitly also tests networkx conversion routing and matrix composition of
transforms.
Thanks to <NAME> for the data set used for comparison.
"""
from astropysics.coords.coordsys import SupergalacticCoordinates,\
GalacticCoordinates,FK5Coordinates
#data set computed with IDL glactc.pro and cross-checks with catalogs
#RA,Dec,Glong,Glat,SGlong,SGlat
s="""
00:02:46.30,-52:46:18,319.1284,-62.7990,242.7085,-4.8166
02:06:15.80,-60:56:24,287.5992,-53.9043,236.4422,-22.3149
04:06:07.90,-52:40:06,261.9954,-45.9695,238.7820,-40.3614
06:00:10.70,-31:47:14,237.7245,-24.0782,241.8464,-69.6481
10:01:33.60,-06:31:30,245.9121,36.8999,110.4980,-43.4303
12:00:47.40,-03:25:12,279.1791,57.0976,116.1007,-13.9687
14:03:34.60,-27:16:47,322.0616,32.8979,147.5406,7.3568
16:09:43.90,-00:06:55,11.5871,35.1849,133.7201,46.2550
20:12:43.20,-03:54:22,38.8727,-19.8409,252.4600,62.5355
22:07:50.90,-43:16:43,355.9298,-53.3561,240.8982,16.3463
""".strip()
fk5s = []
fk2gals = []
gals = []
gal2sgals = []
sgals = []
fk2sgals = []
for l in s.split('\n'):
ls = l.strip().split(',')
fk5s.append(FK5Coordinates(ls[0],ls[1],epoch=2000))
gals.append(GalacticCoordinates(ls[2],ls[3]))
fk2gals.append(fk5s[-1].convert(GalacticCoordinates))
sgals.append(SupergalacticCoordinates(ls[4],ls[5]))
gal2sgals.append(gals[-1].convert(SupergalacticCoordinates))
fk2sgals.append(fk5s[-1].convert(SupergalacticCoordinates))
for i in range(len(fk5s)):
assert (gal2sgals[i]-sgals[i]).arcsec < 1,'Gal->SGal not within 1 arcsec:%f'%(gal2sgals[i]-sgals[i]).arcsec
assert (fk2gals[i]-gals[i]).arcsec < 2,'FK5->Gal not within 2 arcsec:%f'%(fk2gals[i]-gals[i]).arcsec
assert (fk2sgals[i]-sgals[i]).arcsec < 2,'FK5->SGal not within 2 arcsec:%f'%(fk2sgals[i]-sgals[i]).arcsec
#now reverse the conversions just to make sure everything is symmetric
for i in range(len(fk5s)):
fksgalfk = (fk2sgals[i].convert(FK5Coordinates)-fk5s[i]).arcsec
assert fksgalfk < 1e-9,'Fk5->SGal->FK5 too large:%g'%fksgalfk
galsgalgal = (gal2sgals[i].convert(GalacticCoordinates)-gals[i]).arcsec
assert galsgalgal < 1e-9,'Gal->SGal->Gal too large:%g'%galsgalgal
fkgalfk = (fk2gals[i].convert(FK5Coordinates)-fk5s[i]).arcsec
assert galsgalgal < 1e-9,'Fk5->Gal->Fk5 too large:%g'%galsgalgal
return fk5s,fk2gals,gals,gal2sgals,sgals,fk2sgals
def test_main_eq_symm(rasdecs=None):
"""
Test FK4<->FK5<->ICRS<->GCRS coordinate conversions.
"""
from numpy import mgrid,array
from astropysics.coords.coordsys import FK4Coordinates,FK5Coordinates, \
ICRSCoordinates,GCRSCoordinates
if rasdecs is None:
rasdecs = (mgrid[0:360:6j,-80:80:5j]).reshape((2,6*5)).T
gs = [GCRSCoordinates(ra,dec) for ra,dec in rasdecs]
ics,f5s,f4s,f5s2,ics2,gs2 = [],[],[],[],[],[]
for g in gs:
ics.append(g.convert(ICRSCoordinates))
f5s.append(ics[-1].convert(FK5Coordinates))
f4s.append(f5s[-1].convert(FK4Coordinates))
f5s2.append(f4s[-1].convert(FK5Coordinates))
ics2.append(f5s2[-1].convert(ICRSCoordinates))
gs2.append(ics2[-1].convert(GCRSCoordinates))
gdiffs = []
idiffs = []
f5diffs = []
for i in range(len(gs)):
gdiff = (gs[i]-gs2[i]).arcsec
idiff = (ics[i]-ics2[i]).arcsec
f5diff = (f5s[i]-f5s2[i]).arcsec
assert gdiff< 1e-9,'GCRS<-...->GCRS too large:%g'%gdiff
assert idiff< 1e-9,'ICRS<-...->ICRS too large:%g'%idiff
assert f5diff< 1e-9,'FK5<-...->FK5 too large:%g'%f5diff
gdiffs.append(gdiff)
idiffs.append(idiff)
f5diffs.append(f5diff)
return array(gdiffs),array(idiffs),array(f5diffs)
def test_cirs_eqx_symm(rasdecs=None):
"""
Test GCRS<->ITRS and intermediate coordinate conversions.
"""
from numpy import mgrid,array
from astropysics.coords.coordsys import GCRSCoordinates,CIRSCoordinates, \
EquatorialCoordinatesEquinox,ITRSCoordinates
if rasdecs is None:
rasdecs = (mgrid[0:360:6j,-80:80:5j]).reshape((2,6*5)).T
gs = [GCRSCoordinates(ra,dec) for ra,dec in rasdecs]
#through cirs
cs,tcs,cs2,gs2 = [],[],[],[]
for g in gs:
cs.append(g.convert(CIRSCoordinates))
tcs.append(cs[-1].convert(ITRSCoordinates))
cs2.append(tcs[-1].convert(CIRSCoordinates))
gs2.append(cs2[-1].convert(GCRSCoordinates))
for i in range(len(gs)):
gdiff = (gs2[i]-gs[i]).arcsec
#through equinox
eqs,tcs2,eqs2,gs3 = [],[],[],[]
for g in gs:
eqs.append(g.convert(EquatorialCoordinatesEquinox))
tcs2.append(eqs[-1].convert(ITRSCoordinates))
eqs2.append(tcs2[-1].convert(EquatorialCoordinatesEquinox))
gs3.append(eqs2[-1].convert(GCRSCoordinates))
gds1,gds2,tds,cds,eds = [],[],[],[],[]
for i in range(len(gs)):
gdiff1 = (gs2[i]-gs[i]).arcsec
gdiff2 = (gs3[i]-gs[i]).arcsec
tdiff = (tcs2[i]-tcs[i]).arcsec
cdiff = (cs2[i]-cs[i]).arcsec
ediff = (eqs2[i]-eqs[i]).arcsec
assert gdiff1< 5e-10,'GCRS<-..CIRS..->GCRS too large:%g'%gdiff1
assert cdiff< 5e-10,'CIRS->ITRS->CIRS too large:%g'%cdiff
assert gdiff2< 5e-10,'GCRS<-..Equinox..->GCRS too large:%g'%gdiff2
assert ediff< 5e-10,'Eq->ITRS->Eq too large:%g'%ediff
#TODO:fix this difference when equinox->ITRS is fixed
assert tdiff< 60,'GCRS->ITRS between CIRS and Eq too large:%g'%tdiff
gds1.append(gdiff1)
gds2.append(gdiff2)
tds.append(tdiff)
cds.append(cdiff)
eds.append(ediff)
return array(gds1),array(cds),array(gds2),array(eds),array(tds)
def test_cirs_eqx_ecl(rasdecs=None):
"""
Test Ecliptic transforms between CIRS and Equinox.
"""
from numpy import mgrid,array
from astropysics.coords.coordsys import CIRSCoordinates, \
EquatorialCoordinatesEquinox,EclipticCoordinatesCIRS,\
EclipticCoordinatesEquinox,RectangularGeocentricEclipticCoordinates
if rasdecs is None:
rasdecs = (mgrid[0:360:6j,-80:80:5j]).reshape((2,6*5)).T
cs = [CIRSCoordinates(ra,dec) for ra,dec in rasdecs]
ecs,rgs,ecxs,eqxs,ecxs2,rgs2,ecs2,cs2 = [],[],[],[],[],[],[],[]
for c in cs:
ecs.append(c.convert(EclipticCoordinatesCIRS))
rgs.append(ecs[-1].convert(RectangularGeocentricEclipticCoordinates))
ecxs.append(rgs[-1].convert(EclipticCoordinatesEquinox))
eqxs.append(ecxs[-1].convert(EquatorialCoordinatesEquinox))
ecxs2.append(eqxs[-1].convert(EclipticCoordinatesEquinox))
rgs2.append(ecxs2[-1].convert(RectangularGeocentricEclipticCoordinates))
ecs2.append(rgs2[-1].convert(EclipticCoordinatesCIRS))
cs2.append(ecs2[-1].convert(CIRSCoordinates))
cds,ecds,rgds,ecxds = [],[],[],[]
for i in range(len(cs)):
cdiff = (cs2[i]-cs[i]).arcsec
ecdiff = (ecs2[i]-ecs[i]).arcsec
rgdiff = (rgs2[i]-rgs[i]).length
ecxdiff = (ecxs2[i]-ecxs[i]).arcsec
assert cdiff< 5e-10,'CIRS->...->CIRS too large:%g'%cdiff
assert ecdiff< 5e-10,'EcCIRS->...->EcCIRS too large:%g'%ecdiff
assert rgdiff< 2e-15,'RectEc->...->RectEc too large:%g'%rgdiff
assert ecxdiff< 5e-10,'Eqx->...->Eqx too large:%g'%ecxdiff
cds.append(cdiff)
ecds.append(ecdiff)
rgds.append(rgdiff)
ecxds.append(ecxdiff)
return array(cds),array(ecds),array(rgds),array(ecxds)
def test_icrs_rect():
"""
Test ICRSCoordinates <-> RectangularICRSCoordinates conversions.
"""
from astropysics.coords.coordsys import RectangularICRSCoordinates,\
ICRSCoordinates
from numpy import array,mgrid
from numpy.random import randn
from nose.tools import assert_almost_equal
# ntests = 5
# coords = randn(ntests,3)
coords = mgrid[-1.5:1.5:5j,-1.5:1.5:5j,-1.5:1.5:5j].reshape((3,5*5*5)).T
xds,yds,zds = [],[],[]
for x,y,z in coords:
if x==0 and y==0 and z==0:
continue
unit = 'au' if x<0 else 'pc'
r = RectangularICRSCoordinates(x,y,z,unit=unit)
c = r.convert(ICRSCoordinates)
r2 = c.convert(RectangularICRSCoordinates)
c2 = r2.convert(ICRSCoordinates)
r3 = c2.convert(RectangularICRSCoordinates)
r3.unit = unit
#unit conversion only good to ~5 places
assert_almost_equal(x,r3.x,5)
assert_almost_equal(y,r3.y,5)
assert_almost_equal(z,r3.z,5)
xds.append(x-r3.x)
yds.append(y-r3.y)
zds.append(z-r3.z)
return array(xds),array(yds),array(zds)
def test_gcrs_rect():
"""
Test GCRSCoordinates <-> RectangularGCRSCoordinates conversions.
"""
from astropysics.coords.coordsys import RectangularGCRSCoordinates,\
GCRSCoordinates
from numpy import array,mgrid
from numpy.random import randn
from nose.tools import assert_almost_equal
# ntests = 5
# coords = randn(ntests,3)
coords = mgrid[-1.5:1.5:5j,-1.5:1.5:5j,-1.5:1.5:5j].reshape((3,5*5*5)).T
xds,yds,zds = [],[],[]
for x,y,z in coords:
if x==0 and y==0 and z==0:
continue
unit = 'au' if x<0 else 'pc'
r = RectangularGCRSCoordinates(x,y,z,unit=unit)
c = r.convert(GCRSCoordinates)
r2 = c.convert(RectangularGCRSCoordinates)
c2 = r2.convert(GCRSCoordinates)
r3 = c2.convert(RectangularGCRSCoordinates)
r3.unit = unit
#unit conversion only good to ~5 places
assert_almost_equal(x,r3.x,5)
assert_almost_equal(y,r3.y,5)
assert_almost_equal(z,r3.z,5)
xds.append(x-r3.x)
yds.append(y-r3.y)
zds.append(z-r3.z)
return array(xds),array(yds),array(zds)
def test_ecliptic_rect():
"""
Test RectangularGeocentricEclipticCoordinates -> Ecliptic
"""
from astropysics.coords.coordsys import EclipticCoordinatesCIRS,\
EclipticCoordinatesEquinox,\
RectangularGeocentricEclipticCoordinates
from numpy.random import randn
from nose.tools import assert_almost_equal
ntests = 5
coords = randn(ntests,3)
for x,y,z in coords:
r = RectangularGeocentricEclipticCoordinates(x,y,z)
c1 = r.convert(EclipticCoordinatesCIRS)
c2 = r.convert(EclipticCoordinatesEquinox)
r1 = c1.convert(RectangularGeocentricEclipticCoordinates)
r2 = c2.convert(RectangularGeocentricEclipticCoordinates)
places = 7
assert_almost_equal(x,r1.x,places)
assert_almost_equal(y,r1.y,places)
assert_almost_equal(z,r1.z,places)
assert_almost_equal(x,r2.x,places)
assert_almost_equal(y,r2.y,places)
assert_almost_equal(z,r2.z,places)
def test_parallax(plot=False,icoords=None):
from astropysics.coords.coordsys import ICRSCoordinates,GCRSCoordinates, \
RectangularGCRSCoordinates, RectangularICRSCoordinates
from astropysics.constants import asecperrad
from numpy import linspace,array,radians,mean,max
if icoords is None:
e = 23.439214393375188
icoords = [(1,1),(270,90-e),(1,30),(180,-30),(80,-89)]
#icoords = [(1,1),(45,0),(45,-30),(45,-45),(45,-60),(45,-75),(45,-89)]
#icoords = [(360.1,0),(145,0),(145,30),(145,45),(145,60),(145,75),(145,89)]
distpcs = [1 for i in icoords]
epochs = linspace(2000,2001,50)
asdiffs = []
drasall = []
ddecsall = []
icsall = []
gcsall = []
ricsall = []
rgcsall = []
for (ra,dec),d in zip(icoords,distpcs):
ics = []
gcs = []
rics = []
rgcs = []
for e in epochs:
ics.append(ICRSCoordinates(ra,dec,distancepc=d,epoch=e))
gcs.append(ics[-1].convert(GCRSCoordinates))
rics.append(ics[-1].convert(RectangularICRSCoordinates))
rgcs.append(gcs[-1].convert(RectangularGCRSCoordinates))
asdiffs.append([(g-ics[0]).arcsec for g in gcs])
drasall.append([(g.ra.r-ics[0].ra.r)*asecperrad for g in gcs])
ddecsall.append([(g.dec.r-ics[0].dec.r)*asecperrad for g in gcs])
icsall.append(ics)
gcsall.append(gcs)
ricsall.append(rics)
rgcsall.append(rgcs)
asdiffs = array(asdiffs)
if plot:
from matplotlib import pyplot as plt
plt.figure(1)
if plot != 'notclf':
plt.clf()
for asd,ics in zip(asdiffs,icsall):
ic = ics[0]
plt.plot(epochs-2000,asd,label='%.2f,%.2f'%(ic.ra.d,ic.dec.d))
plt.xlabel('epoch - 2000')
plt.ylabel('$\Delta_{\\rm ICRS,GCRS}$')
plt.legend(loc=0)
plt.figure(2)
if plot != 'notclf':
plt.clf()
for dras,ddecs,ics in zip(drasall,ddecsall,icsall):
ic = ics[0]
plt.plot(dras,ddecs,label='%.2f,%.2f'%(ic.ra.d,ic.dec.d))
plt.xlabel('$\Delta$RA')
plt.ylabel('$\Delta$Dec')
plt.xlim(-3,3)
plt.ylim(-3,3)
plt.legend(loc=0)
assert max(asdiffs)<=1.05,'Object at 1 pc moves significantly more than 1 arcsec from center:%.3f'%max(asdiffs)
return epochs,asdiffs,icsall,gcsall,ricsall,rgcsall
def test_EquatorialCoordinatesEquinox_initialization():
"""Check whether EquatorialCooridnatesBase can initialize from objects of its class.
"""
from astropysics.coords.coordsys import EquatorialCoordinatesEquinox
m101 = EquatorialCoordinatesEquinox('14:03:12.510 +54:20:53.10 J2000')
m101.distancepc = (6.7e6,0)
m101_duplicate = EquatorialCoordinatesEquinox(m101)
assert m101_duplicate.ra == m101.ra
assert m101_duplicate.dec == m101.dec
assert m101_duplicate.raerr == m101.raerr
assert m101_duplicate.decerr == m101.decerr
assert m101_duplicate.epoch == m101.epoch
assert m101_duplicate.distancepc == m101.distancepc
def test_FK5Coordinates_string_formatting():
import astropysics
from astropysics.coords.coordsys import FK5Coordinates
from astropysics.coords.coordsys import AngularCoordinate
target_coords = FK5Coordinates(("23:15:00 +35.000 J2000.0"))
d1 = target_coords.dec
d2 = AngularCoordinate("+35.000")
assert d1.getDmsStr( canonical= True) == d2.getDmsStr( canonical= True) | tests/test_coords.py | from __future__ import division,with_statement
from nose.tools import assert_almost_equal
def test_gal():
"""Cross-check Gal <-> Supergal <-> FK5 coordinate conversions.
Implicitly also tests networkx conversion routing and matrix composition of
transforms.
Thanks to <NAME> for the data set used for comparison.
"""
from astropysics.coords.coordsys import SupergalacticCoordinates,\
GalacticCoordinates,FK5Coordinates
#data set computed with IDL glactc.pro and cross-checks with catalogs
#RA,Dec,Glong,Glat,SGlong,SGlat
s="""
00:02:46.30,-52:46:18,319.1284,-62.7990,242.7085,-4.8166
02:06:15.80,-60:56:24,287.5992,-53.9043,236.4422,-22.3149
04:06:07.90,-52:40:06,261.9954,-45.9695,238.7820,-40.3614
06:00:10.70,-31:47:14,237.7245,-24.0782,241.8464,-69.6481
10:01:33.60,-06:31:30,245.9121,36.8999,110.4980,-43.4303
12:00:47.40,-03:25:12,279.1791,57.0976,116.1007,-13.9687
14:03:34.60,-27:16:47,322.0616,32.8979,147.5406,7.3568
16:09:43.90,-00:06:55,11.5871,35.1849,133.7201,46.2550
20:12:43.20,-03:54:22,38.8727,-19.8409,252.4600,62.5355
22:07:50.90,-43:16:43,355.9298,-53.3561,240.8982,16.3463
""".strip()
fk5s = []
fk2gals = []
gals = []
gal2sgals = []
sgals = []
fk2sgals = []
for l in s.split('\n'):
ls = l.strip().split(',')
fk5s.append(FK5Coordinates(ls[0],ls[1],epoch=2000))
gals.append(GalacticCoordinates(ls[2],ls[3]))
fk2gals.append(fk5s[-1].convert(GalacticCoordinates))
sgals.append(SupergalacticCoordinates(ls[4],ls[5]))
gal2sgals.append(gals[-1].convert(SupergalacticCoordinates))
fk2sgals.append(fk5s[-1].convert(SupergalacticCoordinates))
for i in range(len(fk5s)):
assert (gal2sgals[i]-sgals[i]).arcsec < 1,'Gal->SGal not within 1 arcsec:%f'%(gal2sgals[i]-sgals[i]).arcsec
assert (fk2gals[i]-gals[i]).arcsec < 2,'FK5->Gal not within 2 arcsec:%f'%(fk2gals[i]-gals[i]).arcsec
assert (fk2sgals[i]-sgals[i]).arcsec < 2,'FK5->SGal not within 2 arcsec:%f'%(fk2sgals[i]-sgals[i]).arcsec
#now reverse the conversions just to make sure everything is symmetric
for i in range(len(fk5s)):
fksgalfk = (fk2sgals[i].convert(FK5Coordinates)-fk5s[i]).arcsec
assert fksgalfk < 1e-9,'Fk5->SGal->FK5 too large:%g'%fksgalfk
galsgalgal = (gal2sgals[i].convert(GalacticCoordinates)-gals[i]).arcsec
assert galsgalgal < 1e-9,'Gal->SGal->Gal too large:%g'%galsgalgal
fkgalfk = (fk2gals[i].convert(FK5Coordinates)-fk5s[i]).arcsec
assert galsgalgal < 1e-9,'Fk5->Gal->Fk5 too large:%g'%galsgalgal
return fk5s,fk2gals,gals,gal2sgals,sgals,fk2sgals
def test_main_eq_symm(rasdecs=None):
"""
Test FK4<->FK5<->ICRS<->GCRS coordinate conversions.
"""
from numpy import mgrid,array
from astropysics.coords.coordsys import FK4Coordinates,FK5Coordinates, \
ICRSCoordinates,GCRSCoordinates
if rasdecs is None:
rasdecs = (mgrid[0:360:6j,-80:80:5j]).reshape((2,6*5)).T
gs = [GCRSCoordinates(ra,dec) for ra,dec in rasdecs]
ics,f5s,f4s,f5s2,ics2,gs2 = [],[],[],[],[],[]
for g in gs:
ics.append(g.convert(ICRSCoordinates))
f5s.append(ics[-1].convert(FK5Coordinates))
f4s.append(f5s[-1].convert(FK4Coordinates))
f5s2.append(f4s[-1].convert(FK5Coordinates))
ics2.append(f5s2[-1].convert(ICRSCoordinates))
gs2.append(ics2[-1].convert(GCRSCoordinates))
gdiffs = []
idiffs = []
f5diffs = []
for i in range(len(gs)):
gdiff = (gs[i]-gs2[i]).arcsec
idiff = (ics[i]-ics2[i]).arcsec
f5diff = (f5s[i]-f5s2[i]).arcsec
assert gdiff< 1e-9,'GCRS<-...->GCRS too large:%g'%gdiff
assert idiff< 1e-9,'ICRS<-...->ICRS too large:%g'%idiff
assert f5diff< 1e-9,'FK5<-...->FK5 too large:%g'%f5diff
gdiffs.append(gdiff)
idiffs.append(idiff)
f5diffs.append(f5diff)
return array(gdiffs),array(idiffs),array(f5diffs)
def test_cirs_eqx_symm(rasdecs=None):
"""
Test GCRS<->ITRS and intermediate coordinate conversions.
"""
from numpy import mgrid,array
from astropysics.coords.coordsys import GCRSCoordinates,CIRSCoordinates, \
EquatorialCoordinatesEquinox,ITRSCoordinates
if rasdecs is None:
rasdecs = (mgrid[0:360:6j,-80:80:5j]).reshape((2,6*5)).T
gs = [GCRSCoordinates(ra,dec) for ra,dec in rasdecs]
#through cirs
cs,tcs,cs2,gs2 = [],[],[],[]
for g in gs:
cs.append(g.convert(CIRSCoordinates))
tcs.append(cs[-1].convert(ITRSCoordinates))
cs2.append(tcs[-1].convert(CIRSCoordinates))
gs2.append(cs2[-1].convert(GCRSCoordinates))
for i in range(len(gs)):
gdiff = (gs2[i]-gs[i]).arcsec
#through equinox
eqs,tcs2,eqs2,gs3 = [],[],[],[]
for g in gs:
eqs.append(g.convert(EquatorialCoordinatesEquinox))
tcs2.append(eqs[-1].convert(ITRSCoordinates))
eqs2.append(tcs2[-1].convert(EquatorialCoordinatesEquinox))
gs3.append(eqs2[-1].convert(GCRSCoordinates))
gds1,gds2,tds,cds,eds = [],[],[],[],[]
for i in range(len(gs)):
gdiff1 = (gs2[i]-gs[i]).arcsec
gdiff2 = (gs3[i]-gs[i]).arcsec
tdiff = (tcs2[i]-tcs[i]).arcsec
cdiff = (cs2[i]-cs[i]).arcsec
ediff = (eqs2[i]-eqs[i]).arcsec
assert gdiff1< 5e-10,'GCRS<-..CIRS..->GCRS too large:%g'%gdiff1
assert cdiff< 5e-10,'CIRS->ITRS->CIRS too large:%g'%cdiff
assert gdiff2< 5e-10,'GCRS<-..Equinox..->GCRS too large:%g'%gdiff2
assert ediff< 5e-10,'Eq->ITRS->Eq too large:%g'%ediff
#TODO:fix this difference when equinox->ITRS is fixed
assert tdiff< 60,'GCRS->ITRS between CIRS and Eq too large:%g'%tdiff
gds1.append(gdiff1)
gds2.append(gdiff2)
tds.append(tdiff)
cds.append(cdiff)
eds.append(ediff)
return array(gds1),array(cds),array(gds2),array(eds),array(tds)
def test_cirs_eqx_ecl(rasdecs=None):
"""
Test Ecliptic transforms between CIRS and Equinox.
"""
from numpy import mgrid,array
from astropysics.coords.coordsys import CIRSCoordinates, \
EquatorialCoordinatesEquinox,EclipticCoordinatesCIRS,\
EclipticCoordinatesEquinox,RectangularGeocentricEclipticCoordinates
if rasdecs is None:
rasdecs = (mgrid[0:360:6j,-80:80:5j]).reshape((2,6*5)).T
cs = [CIRSCoordinates(ra,dec) for ra,dec in rasdecs]
ecs,rgs,ecxs,eqxs,ecxs2,rgs2,ecs2,cs2 = [],[],[],[],[],[],[],[]
for c in cs:
ecs.append(c.convert(EclipticCoordinatesCIRS))
rgs.append(ecs[-1].convert(RectangularGeocentricEclipticCoordinates))
ecxs.append(rgs[-1].convert(EclipticCoordinatesEquinox))
eqxs.append(ecxs[-1].convert(EquatorialCoordinatesEquinox))
ecxs2.append(eqxs[-1].convert(EclipticCoordinatesEquinox))
rgs2.append(ecxs2[-1].convert(RectangularGeocentricEclipticCoordinates))
ecs2.append(rgs2[-1].convert(EclipticCoordinatesCIRS))
cs2.append(ecs2[-1].convert(CIRSCoordinates))
cds,ecds,rgds,ecxds = [],[],[],[]
for i in range(len(cs)):
cdiff = (cs2[i]-cs[i]).arcsec
ecdiff = (ecs2[i]-ecs[i]).arcsec
rgdiff = (rgs2[i]-rgs[i]).length
ecxdiff = (ecxs2[i]-ecxs[i]).arcsec
assert cdiff< 5e-10,'CIRS->...->CIRS too large:%g'%cdiff
assert ecdiff< 5e-10,'EcCIRS->...->EcCIRS too large:%g'%ecdiff
assert rgdiff< 2e-15,'RectEc->...->RectEc too large:%g'%rgdiff
assert ecxdiff< 5e-10,'Eqx->...->Eqx too large:%g'%ecxdiff
cds.append(cdiff)
ecds.append(ecdiff)
rgds.append(rgdiff)
ecxds.append(ecxdiff)
return array(cds),array(ecds),array(rgds),array(ecxds)
def test_icrs_rect():
"""
Test ICRSCoordinates <-> RectangularICRSCoordinates conversions.
"""
from astropysics.coords.coordsys import RectangularICRSCoordinates,\
ICRSCoordinates
from numpy import array,mgrid
from numpy.random import randn
from nose.tools import assert_almost_equal
# ntests = 5
# coords = randn(ntests,3)
coords = mgrid[-1.5:1.5:5j,-1.5:1.5:5j,-1.5:1.5:5j].reshape((3,5*5*5)).T
xds,yds,zds = [],[],[]
for x,y,z in coords:
if x==0 and y==0 and z==0:
continue
unit = 'au' if x<0 else 'pc'
r = RectangularICRSCoordinates(x,y,z,unit=unit)
c = r.convert(ICRSCoordinates)
r2 = c.convert(RectangularICRSCoordinates)
c2 = r2.convert(ICRSCoordinates)
r3 = c2.convert(RectangularICRSCoordinates)
r3.unit = unit
#unit conversion only good to ~5 places
assert_almost_equal(x,r3.x,5)
assert_almost_equal(y,r3.y,5)
assert_almost_equal(z,r3.z,5)
xds.append(x-r3.x)
yds.append(y-r3.y)
zds.append(z-r3.z)
return array(xds),array(yds),array(zds)
def test_gcrs_rect():
"""
Test GCRSCoordinates <-> RectangularGCRSCoordinates conversions.
"""
from astropysics.coords.coordsys import RectangularGCRSCoordinates,\
GCRSCoordinates
from numpy import array,mgrid
from numpy.random import randn
from nose.tools import assert_almost_equal
# ntests = 5
# coords = randn(ntests,3)
coords = mgrid[-1.5:1.5:5j,-1.5:1.5:5j,-1.5:1.5:5j].reshape((3,5*5*5)).T
xds,yds,zds = [],[],[]
for x,y,z in coords:
if x==0 and y==0 and z==0:
continue
unit = 'au' if x<0 else 'pc'
r = RectangularGCRSCoordinates(x,y,z,unit=unit)
c = r.convert(GCRSCoordinates)
r2 = c.convert(RectangularGCRSCoordinates)
c2 = r2.convert(GCRSCoordinates)
r3 = c2.convert(RectangularGCRSCoordinates)
r3.unit = unit
#unit conversion only good to ~5 places
assert_almost_equal(x,r3.x,5)
assert_almost_equal(y,r3.y,5)
assert_almost_equal(z,r3.z,5)
xds.append(x-r3.x)
yds.append(y-r3.y)
zds.append(z-r3.z)
return array(xds),array(yds),array(zds)
def test_ecliptic_rect():
"""
Test RectangularGeocentricEclipticCoordinates -> Ecliptic
"""
from astropysics.coords.coordsys import EclipticCoordinatesCIRS,\
EclipticCoordinatesEquinox,\
RectangularGeocentricEclipticCoordinates
from numpy.random import randn
from nose.tools import assert_almost_equal
ntests = 5
coords = randn(ntests,3)
for x,y,z in coords:
r = RectangularGeocentricEclipticCoordinates(x,y,z)
c1 = r.convert(EclipticCoordinatesCIRS)
c2 = r.convert(EclipticCoordinatesEquinox)
r1 = c1.convert(RectangularGeocentricEclipticCoordinates)
r2 = c2.convert(RectangularGeocentricEclipticCoordinates)
places = 7
assert_almost_equal(x,r1.x,places)
assert_almost_equal(y,r1.y,places)
assert_almost_equal(z,r1.z,places)
assert_almost_equal(x,r2.x,places)
assert_almost_equal(y,r2.y,places)
assert_almost_equal(z,r2.z,places)
def test_parallax(plot=False,icoords=None):
from astropysics.coords.coordsys import ICRSCoordinates,GCRSCoordinates, \
RectangularGCRSCoordinates, RectangularICRSCoordinates
from astropysics.constants import asecperrad
from numpy import linspace,array,radians,mean,max
if icoords is None:
e = 23.439214393375188
icoords = [(1,1),(270,90-e),(1,30),(180,-30),(80,-89)]
#icoords = [(1,1),(45,0),(45,-30),(45,-45),(45,-60),(45,-75),(45,-89)]
#icoords = [(360.1,0),(145,0),(145,30),(145,45),(145,60),(145,75),(145,89)]
distpcs = [1 for i in icoords]
epochs = linspace(2000,2001,50)
asdiffs = []
drasall = []
ddecsall = []
icsall = []
gcsall = []
ricsall = []
rgcsall = []
for (ra,dec),d in zip(icoords,distpcs):
ics = []
gcs = []
rics = []
rgcs = []
for e in epochs:
ics.append(ICRSCoordinates(ra,dec,distancepc=d,epoch=e))
gcs.append(ics[-1].convert(GCRSCoordinates))
rics.append(ics[-1].convert(RectangularICRSCoordinates))
rgcs.append(gcs[-1].convert(RectangularGCRSCoordinates))
asdiffs.append([(g-ics[0]).arcsec for g in gcs])
drasall.append([(g.ra.r-ics[0].ra.r)*asecperrad for g in gcs])
ddecsall.append([(g.dec.r-ics[0].dec.r)*asecperrad for g in gcs])
icsall.append(ics)
gcsall.append(gcs)
ricsall.append(rics)
rgcsall.append(rgcs)
asdiffs = array(asdiffs)
if plot:
from matplotlib import pyplot as plt
plt.figure(1)
if plot != 'notclf':
plt.clf()
for asd,ics in zip(asdiffs,icsall):
ic = ics[0]
plt.plot(epochs-2000,asd,label='%.2f,%.2f'%(ic.ra.d,ic.dec.d))
plt.xlabel('epoch - 2000')
plt.ylabel('$\Delta_{\\rm ICRS,GCRS}$')
plt.legend(loc=0)
plt.figure(2)
if plot != 'notclf':
plt.clf()
for dras,ddecs,ics in zip(drasall,ddecsall,icsall):
ic = ics[0]
plt.plot(dras,ddecs,label='%.2f,%.2f'%(ic.ra.d,ic.dec.d))
plt.xlabel('$\Delta$RA')
plt.ylabel('$\Delta$Dec')
plt.xlim(-3,3)
plt.ylim(-3,3)
plt.legend(loc=0)
assert max(asdiffs)<=1.05,'Object at 1 pc moves significantly more than 1 arcsec from center:%.3f'%max(asdiffs)
return epochs,asdiffs,icsall,gcsall,ricsall,rgcsall
def test_EquatorialCoordinatesEquinox_initialization():
"""Check whether EquatorialCooridnatesBase can initialize from objects of its class.
"""
from astropysics.coords.coordsys import EquatorialCoordinatesEquinox
m101 = EquatorialCoordinatesEquinox('14:03:12.510 +54:20:53.10 J2000')
m101.distancepc = (6.7e6,0)
m101_duplicate = EquatorialCoordinatesEquinox(m101)
assert m101_duplicate.ra == m101.ra
assert m101_duplicate.dec == m101.dec
assert m101_duplicate.raerr == m101.raerr
assert m101_duplicate.decerr == m101.decerr
assert m101_duplicate.epoch == m101.epoch
assert m101_duplicate.distancepc == m101.distancepc
def test_FK5Coordinates_string_formatting():
import astropysics
from astropysics.coords.coordsys import FK5Coordinates
from astropysics.coords.coordsys import AngularCoordinate
target_coords = FK5Coordinates(("23:15:00 +35.000 J2000.0"))
d1 = target_coords.dec
d2 = AngularCoordinate("+35.000")
assert d1.getDmsStr( canonical= True) == d2.getDmsStr( canonical= True) | 0.372505 | 0.517998 |
import torch
import torch.nn as nn
from neuroir.inputters import BOS, PAD
from neuroir.modules.embeddings import Embeddings
from neuroir.encoders.rnn_encoder import RNNEncoder
from neuroir.decoders.rnn_decoder import RNNDecoder
class Embedder(nn.Module):
def __init__(self,
emsize,
src_vocab_size,
dropout_emb):
super(Embedder, self).__init__()
self.word_embeddings = Embeddings(emsize,
src_vocab_size,
PAD)
self.output_size = emsize
self.dropout = nn.Dropout(dropout_emb)
def forward(self,
sequence):
word_rep = self.word_embeddings(sequence.unsqueeze(2)) # B x P x d
word_rep = self.dropout(word_rep)
return word_rep
class Encoder(nn.Module):
def __init__(self,
rnn_type,
input_size,
bidirection,
nlayers,
nhid,
dropout_rnn):
super(Encoder, self).__init__()
self.encoder = RNNEncoder(rnn_type,
input_size,
bidirection,
nlayers,
nhid,
dropout_rnn)
def forward(self,
input,
input_len,
init_states=None):
hidden, M = self.encoder(input,
input_len,
init_states) # B x Seq-len x h
return hidden, M
class Decoder(nn.Module):
def __init__(self,
rnn_type,
input_size,
bidirection,
nlayers,
nhid,
attn_type,
dropout_rnn,
copy_attn,
reuse_copy_attn):
super(Decoder, self).__init__()
attn_type = None if attn_type == 'none' else attn_type
self.decoder = RNNDecoder(rnn_type,
input_size,
bidirection,
nlayers,
nhid,
attn_type=attn_type,
dropout=dropout_rnn,
copy_attn=copy_attn,
reuse_copy_attn=reuse_copy_attn)
def init_decoder(self, hidden):
return self.decoder.init_decoder_state(hidden)
def forward(self,
tgt,
memory_bank,
memory_len,
state):
decoder_outputs, _, attns = self.decoder(tgt,
memory_bank,
state,
memory_lengths=memory_len)
return decoder_outputs, attns | neuroir/recommender/layers.py | import torch
import torch.nn as nn
from neuroir.inputters import BOS, PAD
from neuroir.modules.embeddings import Embeddings
from neuroir.encoders.rnn_encoder import RNNEncoder
from neuroir.decoders.rnn_decoder import RNNDecoder
class Embedder(nn.Module):
def __init__(self,
emsize,
src_vocab_size,
dropout_emb):
super(Embedder, self).__init__()
self.word_embeddings = Embeddings(emsize,
src_vocab_size,
PAD)
self.output_size = emsize
self.dropout = nn.Dropout(dropout_emb)
def forward(self,
sequence):
word_rep = self.word_embeddings(sequence.unsqueeze(2)) # B x P x d
word_rep = self.dropout(word_rep)
return word_rep
class Encoder(nn.Module):
def __init__(self,
rnn_type,
input_size,
bidirection,
nlayers,
nhid,
dropout_rnn):
super(Encoder, self).__init__()
self.encoder = RNNEncoder(rnn_type,
input_size,
bidirection,
nlayers,
nhid,
dropout_rnn)
def forward(self,
input,
input_len,
init_states=None):
hidden, M = self.encoder(input,
input_len,
init_states) # B x Seq-len x h
return hidden, M
class Decoder(nn.Module):
def __init__(self,
rnn_type,
input_size,
bidirection,
nlayers,
nhid,
attn_type,
dropout_rnn,
copy_attn,
reuse_copy_attn):
super(Decoder, self).__init__()
attn_type = None if attn_type == 'none' else attn_type
self.decoder = RNNDecoder(rnn_type,
input_size,
bidirection,
nlayers,
nhid,
attn_type=attn_type,
dropout=dropout_rnn,
copy_attn=copy_attn,
reuse_copy_attn=reuse_copy_attn)
def init_decoder(self, hidden):
return self.decoder.init_decoder_state(hidden)
def forward(self,
tgt,
memory_bank,
memory_len,
state):
decoder_outputs, _, attns = self.decoder(tgt,
memory_bank,
state,
memory_lengths=memory_len)
return decoder_outputs, attns | 0.909717 | 0.169097 |
from pprint import pformat
from six import iteritems
import re
class DeviceEventData(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'changes': 'dict(str, str)',
'created_at': 'datetime',
'data': 'object',
'date_time': 'datetime',
'description': 'str',
'device_id': 'str',
'etag': 'datetime',
'event_type': 'str',
'event_type_category': 'str',
'event_type_description': 'str',
'id': 'str',
'object': 'str',
'state_change': 'bool'
}
attribute_map = {
'changes': 'changes',
'created_at': 'created_at',
'data': 'data',
'date_time': 'date_time',
'description': 'description',
'device_id': 'device_id',
'etag': 'etag',
'event_type': 'event_type',
'event_type_category': 'event_type_category',
'event_type_description': 'event_type_description',
'id': 'id',
'object': 'object',
'state_change': 'state_change'
}
def __init__(self, changes=None, created_at=None, data=None, date_time=None, description=None, device_id=None, etag=None, event_type=None, event_type_category=None, event_type_description=None, id=None, object=None, state_change=None):
"""
DeviceEventData - a model defined in Swagger
"""
self._changes = changes
self._created_at = created_at
self._data = data
self._date_time = date_time
self._description = description
self._device_id = device_id
self._etag = etag
self._event_type = event_type
self._event_type_category = event_type_category
self._event_type_description = event_type_description
self._id = id
self._object = object
self._state_change = state_change
self.discriminator = None
@property
def changes(self):
"""
Gets the changes of this DeviceEventData.
Additional data relevant to the event.
:return: The changes of this DeviceEventData.
:rtype: dict(str, str)
"""
return self._changes
@changes.setter
def changes(self, changes):
"""
Sets the changes of this DeviceEventData.
Additional data relevant to the event.
:param changes: The changes of this DeviceEventData.
:type: dict(str, str)
"""
self._changes = changes
@property
def created_at(self):
"""
Gets the created_at of this DeviceEventData.
:return: The created_at of this DeviceEventData.
:rtype: datetime
"""
return self._created_at
@created_at.setter
def created_at(self, created_at):
"""
Sets the created_at of this DeviceEventData.
:param created_at: The created_at of this DeviceEventData.
:type: datetime
"""
self._created_at = created_at
@property
def data(self):
"""
Gets the data of this DeviceEventData.
:return: The data of this DeviceEventData.
:rtype: object
"""
return self._data
@data.setter
def data(self, data):
"""
Sets the data of this DeviceEventData.
:param data: The data of this DeviceEventData.
:type: object
"""
self._data = data
@property
def date_time(self):
"""
Gets the date_time of this DeviceEventData.
:return: The date_time of this DeviceEventData.
:rtype: datetime
"""
return self._date_time
@date_time.setter
def date_time(self, date_time):
"""
Sets the date_time of this DeviceEventData.
:param date_time: The date_time of this DeviceEventData.
:type: datetime
"""
if date_time is None:
raise ValueError("Invalid value for `date_time`, must not be `None`")
self._date_time = date_time
@property
def description(self):
"""
Gets the description of this DeviceEventData.
:return: The description of this DeviceEventData.
:rtype: str
"""
return self._description
@description.setter
def description(self, description):
"""
Sets the description of this DeviceEventData.
:param description: The description of this DeviceEventData.
:type: str
"""
self._description = description
@property
def device_id(self):
"""
Gets the device_id of this DeviceEventData.
:return: The device_id of this DeviceEventData.
:rtype: str
"""
return self._device_id
@device_id.setter
def device_id(self, device_id):
"""
Sets the device_id of this DeviceEventData.
:param device_id: The device_id of this DeviceEventData.
:type: str
"""
self._device_id = device_id
@property
def etag(self):
"""
Gets the etag of this DeviceEventData.
:return: The etag of this DeviceEventData.
:rtype: datetime
"""
return self._etag
@etag.setter
def etag(self, etag):
"""
Sets the etag of this DeviceEventData.
:param etag: The etag of this DeviceEventData.
:type: datetime
"""
self._etag = etag
@property
def event_type(self):
"""
Gets the event_type of this DeviceEventData.
Event code
:return: The event_type of this DeviceEventData.
:rtype: str
"""
return self._event_type
@event_type.setter
def event_type(self, event_type):
"""
Sets the event_type of this DeviceEventData.
Event code
:param event_type: The event_type of this DeviceEventData.
:type: str
"""
if event_type is not None and len(event_type) > 100:
raise ValueError("Invalid value for `event_type`, length must be less than or equal to `100`")
self._event_type = event_type
@property
def event_type_category(self):
"""
Gets the event_type_category of this DeviceEventData.
Category code which groups the event type by a summary category.
:return: The event_type_category of this DeviceEventData.
:rtype: str
"""
return self._event_type_category
@event_type_category.setter
def event_type_category(self, event_type_category):
"""
Sets the event_type_category of this DeviceEventData.
Category code which groups the event type by a summary category.
:param event_type_category: The event_type_category of this DeviceEventData.
:type: str
"""
self._event_type_category = event_type_category
@property
def event_type_description(self):
"""
Gets the event_type_description of this DeviceEventData.
Generic description of the event
:return: The event_type_description of this DeviceEventData.
:rtype: str
"""
return self._event_type_description
@event_type_description.setter
def event_type_description(self, event_type_description):
"""
Sets the event_type_description of this DeviceEventData.
Generic description of the event
:param event_type_description: The event_type_description of this DeviceEventData.
:type: str
"""
self._event_type_description = event_type_description
@property
def id(self):
"""
Gets the id of this DeviceEventData.
:return: The id of this DeviceEventData.
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""
Sets the id of this DeviceEventData.
:param id: The id of this DeviceEventData.
:type: str
"""
if id is None:
raise ValueError("Invalid value for `id`, must not be `None`")
self._id = id
@property
def object(self):
"""
Gets the object of this DeviceEventData.
The API resource entity.
:return: The object of this DeviceEventData.
:rtype: str
"""
return self._object
@object.setter
def object(self, object):
"""
Sets the object of this DeviceEventData.
The API resource entity.
:param object: The object of this DeviceEventData.
:type: str
"""
self._object = object
@property
def state_change(self):
"""
Gets the state_change of this DeviceEventData.
:return: The state_change of this DeviceEventData.
:rtype: bool
"""
return self._state_change
@state_change.setter
def state_change(self, state_change):
"""
Sets the state_change of this DeviceEventData.
:param state_change: The state_change of this DeviceEventData.
:type: bool
"""
self._state_change = state_change
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, DeviceEventData):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other | src/mbed_cloud/_backends/device_directory/models/device_event_data.py | from pprint import pformat
from six import iteritems
import re
class DeviceEventData(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'changes': 'dict(str, str)',
'created_at': 'datetime',
'data': 'object',
'date_time': 'datetime',
'description': 'str',
'device_id': 'str',
'etag': 'datetime',
'event_type': 'str',
'event_type_category': 'str',
'event_type_description': 'str',
'id': 'str',
'object': 'str',
'state_change': 'bool'
}
attribute_map = {
'changes': 'changes',
'created_at': 'created_at',
'data': 'data',
'date_time': 'date_time',
'description': 'description',
'device_id': 'device_id',
'etag': 'etag',
'event_type': 'event_type',
'event_type_category': 'event_type_category',
'event_type_description': 'event_type_description',
'id': 'id',
'object': 'object',
'state_change': 'state_change'
}
def __init__(self, changes=None, created_at=None, data=None, date_time=None, description=None, device_id=None, etag=None, event_type=None, event_type_category=None, event_type_description=None, id=None, object=None, state_change=None):
"""
DeviceEventData - a model defined in Swagger
"""
self._changes = changes
self._created_at = created_at
self._data = data
self._date_time = date_time
self._description = description
self._device_id = device_id
self._etag = etag
self._event_type = event_type
self._event_type_category = event_type_category
self._event_type_description = event_type_description
self._id = id
self._object = object
self._state_change = state_change
self.discriminator = None
@property
def changes(self):
"""
Gets the changes of this DeviceEventData.
Additional data relevant to the event.
:return: The changes of this DeviceEventData.
:rtype: dict(str, str)
"""
return self._changes
@changes.setter
def changes(self, changes):
"""
Sets the changes of this DeviceEventData.
Additional data relevant to the event.
:param changes: The changes of this DeviceEventData.
:type: dict(str, str)
"""
self._changes = changes
@property
def created_at(self):
"""
Gets the created_at of this DeviceEventData.
:return: The created_at of this DeviceEventData.
:rtype: datetime
"""
return self._created_at
@created_at.setter
def created_at(self, created_at):
"""
Sets the created_at of this DeviceEventData.
:param created_at: The created_at of this DeviceEventData.
:type: datetime
"""
self._created_at = created_at
@property
def data(self):
"""
Gets the data of this DeviceEventData.
:return: The data of this DeviceEventData.
:rtype: object
"""
return self._data
@data.setter
def data(self, data):
"""
Sets the data of this DeviceEventData.
:param data: The data of this DeviceEventData.
:type: object
"""
self._data = data
@property
def date_time(self):
"""
Gets the date_time of this DeviceEventData.
:return: The date_time of this DeviceEventData.
:rtype: datetime
"""
return self._date_time
@date_time.setter
def date_time(self, date_time):
"""
Sets the date_time of this DeviceEventData.
:param date_time: The date_time of this DeviceEventData.
:type: datetime
"""
if date_time is None:
raise ValueError("Invalid value for `date_time`, must not be `None`")
self._date_time = date_time
@property
def description(self):
"""
Gets the description of this DeviceEventData.
:return: The description of this DeviceEventData.
:rtype: str
"""
return self._description
@description.setter
def description(self, description):
"""
Sets the description of this DeviceEventData.
:param description: The description of this DeviceEventData.
:type: str
"""
self._description = description
@property
def device_id(self):
"""
Gets the device_id of this DeviceEventData.
:return: The device_id of this DeviceEventData.
:rtype: str
"""
return self._device_id
@device_id.setter
def device_id(self, device_id):
"""
Sets the device_id of this DeviceEventData.
:param device_id: The device_id of this DeviceEventData.
:type: str
"""
self._device_id = device_id
@property
def etag(self):
"""
Gets the etag of this DeviceEventData.
:return: The etag of this DeviceEventData.
:rtype: datetime
"""
return self._etag
@etag.setter
def etag(self, etag):
"""
Sets the etag of this DeviceEventData.
:param etag: The etag of this DeviceEventData.
:type: datetime
"""
self._etag = etag
@property
def event_type(self):
"""
Gets the event_type of this DeviceEventData.
Event code
:return: The event_type of this DeviceEventData.
:rtype: str
"""
return self._event_type
@event_type.setter
def event_type(self, event_type):
"""
Sets the event_type of this DeviceEventData.
Event code
:param event_type: The event_type of this DeviceEventData.
:type: str
"""
if event_type is not None and len(event_type) > 100:
raise ValueError("Invalid value for `event_type`, length must be less than or equal to `100`")
self._event_type = event_type
@property
def event_type_category(self):
"""
Gets the event_type_category of this DeviceEventData.
Category code which groups the event type by a summary category.
:return: The event_type_category of this DeviceEventData.
:rtype: str
"""
return self._event_type_category
@event_type_category.setter
def event_type_category(self, event_type_category):
"""
Sets the event_type_category of this DeviceEventData.
Category code which groups the event type by a summary category.
:param event_type_category: The event_type_category of this DeviceEventData.
:type: str
"""
self._event_type_category = event_type_category
@property
def event_type_description(self):
"""
Gets the event_type_description of this DeviceEventData.
Generic description of the event
:return: The event_type_description of this DeviceEventData.
:rtype: str
"""
return self._event_type_description
@event_type_description.setter
def event_type_description(self, event_type_description):
"""
Sets the event_type_description of this DeviceEventData.
Generic description of the event
:param event_type_description: The event_type_description of this DeviceEventData.
:type: str
"""
self._event_type_description = event_type_description
@property
def id(self):
"""
Gets the id of this DeviceEventData.
:return: The id of this DeviceEventData.
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""
Sets the id of this DeviceEventData.
:param id: The id of this DeviceEventData.
:type: str
"""
if id is None:
raise ValueError("Invalid value for `id`, must not be `None`")
self._id = id
@property
def object(self):
"""
Gets the object of this DeviceEventData.
The API resource entity.
:return: The object of this DeviceEventData.
:rtype: str
"""
return self._object
@object.setter
def object(self, object):
"""
Sets the object of this DeviceEventData.
The API resource entity.
:param object: The object of this DeviceEventData.
:type: str
"""
self._object = object
@property
def state_change(self):
"""
Gets the state_change of this DeviceEventData.
:return: The state_change of this DeviceEventData.
:rtype: bool
"""
return self._state_change
@state_change.setter
def state_change(self, state_change):
"""
Sets the state_change of this DeviceEventData.
:param state_change: The state_change of this DeviceEventData.
:type: bool
"""
self._state_change = state_change
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, DeviceEventData):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other | 0.719285 | 0.222468 |
import chemlib
import discord
from discord.ext import commands
from discord import Button, ButtonStyle
class Commands(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(aliases=['Element'])
async def element(self, ctx, arg=None):
if arg is None:
await ctx.send(embed=discord.Embed.from_dict({
"title": "Error",
"description": "No input. Please use the command in the form:\n```c!Element <symbol>```"
}))
return
try:
information = chemlib.Element(arg)
element = information['Element']
# Created embed and a copy for when disabling button
embed = discord.Embed(title=element, color=discord.Colour.gold())
em1 = embed
embed.set_thumbnail(url=f'https://images-of-elements.com/t/{element.lower()}.png')
embed.add_field(name='Symbol', value=information['Symbol'])
embed.add_field(name='Atomic Number', value=f"{int(information['AtomicNumber'])}")
embed.add_field(name='Atomic Mass', value=information['AtomicMass'])
embed.add_field(name='Type', value=information['Type'])
phase = information['Phase']
embed.add_field(name='Phase', value=phase[0].upper() + phase[1:])
embed.add_field(name='Electronegativity', value=information['Electronegativity'])
embed.add_field(name='Electron Config', value=information['Config'])
embed.add_field(name='Melting Point', value=f"{information['MeltingPoint']} K")
embed.add_field(name='Boiling Point', value=f"{information['BoilingPoint']} K")
# Sends first embed with condensed info + Button
msg = await ctx.send(embed=embed, components=[Button(label='Full info', custom_id='element_full', style=ButtonStyle.blurple)])
# Waits for user to click button
def check_button(i: discord.Interaction, button):
return i.message == msg
interaction, button = await self.client.wait_for('button_click', check=check_button)
# Adds the rest of the information to the embed
embed.add_field(name='Neutrons-Protons-Electrons',
value=f"{int(information['Neutrons'])}, {int(information['Protons'])}, {int(information['Electrons'])}")
embed.add_field(name='Radioactive', value=f"{information['Radioactive']}")
embed.add_field(name='Specific Heat', value=f"{information['SpecificHeat']} J/(g°C)")
embed.add_field(name='Phase at STP', value=f"{information['Phase']}")
embed.add_field(name='Density', value=f"{information['Density']} g/cm³")
embed.add_field(name='Group', value=f"{information['Group']}")
embed.add_field(name='Period', value=f"{information['Period']}")
# Updates embed to one with disabled button, then sends hidden embed with full info.
await interaction.respond(embed=embed, hidden=True)
await msg.edit(embed=em1, components=[Button(label='Full info', custom_id='element_full', style=ButtonStyle.blurple, disabled=True)])
except IndexError:
await ctx.send("Invalid element symbol. Example of usage: `c!Element Pb`")
except Exception as e:
await ctx.send(embed=discord.Embed.from_dict({"title": "Error",
"description": "Something went wrong..."}))
with open("data/error_log.txt", "a") as file:
file.write(f"[Element]: {e}\n")
@commands.command(aliases=["Constants"])
async def constants(self, ctx):
try:
constants = discord.Embed.from_dict({
"title": "Common Constants",
"color": 0xf1c40f,
"fields": [
{"name": "Avogadro's Number", "value": "6.022 14 × 10²³ mol⁻¹"},
{"name": "Faraday Constant", "value": "96 485.33 C mol⁻¹"},
{"name": "Atomic Mass Constant", "value": "1 amu = 1.660 538 × 10⁻²⁷ kg"},
{"name": "Molar Gas Constant", "value": "8.3144 J mol⁻¹ K⁻¹, 0.082057 L atm K⁻¹ mol⁻¹"},
{"name": "Coulomb's Constant", "value": "8.987551 × 10⁹ N m² C⁻²"},
{"name": "Light Speed (Vacuum)", "value": "299 792 558 m s⁻¹"},
{"name": "Boltzmann Constant", "value": "1.38065 × 10⁻²³ J K⁻¹"},
{"name": "Electron Charge", "value": "1.602176 × 10⁻¹⁹ C"},
{"name": "Standard gravity", "value": "9.80665 m s⁻²"},
{"name": "Rydberg Constant", "value": "1.097373 × 10⁷ m⁻¹"},
{"name": "Planck's Constant", "value": "6.62607 × 10⁻³⁴ J S"}
],
"footer": {"text": "Use 'c!suggestion' to suggest more constants!"}
})
await ctx.send(embed=constants)
except Exception as e:
await ctx.send(embed=discord.Embed.from_dict({"title": "Error",
"description": "Something went wrong..."}))
with open("data/error_log.txt", "a") as file:
file.write(f"[Constants]: {e}\n")
def setup(client):
client.add_cog(Commands(client)) | cogs/chem_info.py | import chemlib
import discord
from discord.ext import commands
from discord import Button, ButtonStyle
class Commands(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(aliases=['Element'])
async def element(self, ctx, arg=None):
if arg is None:
await ctx.send(embed=discord.Embed.from_dict({
"title": "Error",
"description": "No input. Please use the command in the form:\n```c!Element <symbol>```"
}))
return
try:
information = chemlib.Element(arg)
element = information['Element']
# Created embed and a copy for when disabling button
embed = discord.Embed(title=element, color=discord.Colour.gold())
em1 = embed
embed.set_thumbnail(url=f'https://images-of-elements.com/t/{element.lower()}.png')
embed.add_field(name='Symbol', value=information['Symbol'])
embed.add_field(name='Atomic Number', value=f"{int(information['AtomicNumber'])}")
embed.add_field(name='Atomic Mass', value=information['AtomicMass'])
embed.add_field(name='Type', value=information['Type'])
phase = information['Phase']
embed.add_field(name='Phase', value=phase[0].upper() + phase[1:])
embed.add_field(name='Electronegativity', value=information['Electronegativity'])
embed.add_field(name='Electron Config', value=information['Config'])
embed.add_field(name='Melting Point', value=f"{information['MeltingPoint']} K")
embed.add_field(name='Boiling Point', value=f"{information['BoilingPoint']} K")
# Sends first embed with condensed info + Button
msg = await ctx.send(embed=embed, components=[Button(label='Full info', custom_id='element_full', style=ButtonStyle.blurple)])
# Waits for user to click button
def check_button(i: discord.Interaction, button):
return i.message == msg
interaction, button = await self.client.wait_for('button_click', check=check_button)
# Adds the rest of the information to the embed
embed.add_field(name='Neutrons-Protons-Electrons',
value=f"{int(information['Neutrons'])}, {int(information['Protons'])}, {int(information['Electrons'])}")
embed.add_field(name='Radioactive', value=f"{information['Radioactive']}")
embed.add_field(name='Specific Heat', value=f"{information['SpecificHeat']} J/(g°C)")
embed.add_field(name='Phase at STP', value=f"{information['Phase']}")
embed.add_field(name='Density', value=f"{information['Density']} g/cm³")
embed.add_field(name='Group', value=f"{information['Group']}")
embed.add_field(name='Period', value=f"{information['Period']}")
# Updates embed to one with disabled button, then sends hidden embed with full info.
await interaction.respond(embed=embed, hidden=True)
await msg.edit(embed=em1, components=[Button(label='Full info', custom_id='element_full', style=ButtonStyle.blurple, disabled=True)])
except IndexError:
await ctx.send("Invalid element symbol. Example of usage: `c!Element Pb`")
except Exception as e:
await ctx.send(embed=discord.Embed.from_dict({"title": "Error",
"description": "Something went wrong..."}))
with open("data/error_log.txt", "a") as file:
file.write(f"[Element]: {e}\n")
@commands.command(aliases=["Constants"])
async def constants(self, ctx):
try:
constants = discord.Embed.from_dict({
"title": "Common Constants",
"color": 0xf1c40f,
"fields": [
{"name": "Avogadro's Number", "value": "6.022 14 × 10²³ mol⁻¹"},
{"name": "Faraday Constant", "value": "96 485.33 C mol⁻¹"},
{"name": "Atomic Mass Constant", "value": "1 amu = 1.660 538 × 10⁻²⁷ kg"},
{"name": "Molar Gas Constant", "value": "8.3144 J mol⁻¹ K⁻¹, 0.082057 L atm K⁻¹ mol⁻¹"},
{"name": "Coulomb's Constant", "value": "8.987551 × 10⁹ N m² C⁻²"},
{"name": "Light Speed (Vacuum)", "value": "299 792 558 m s⁻¹"},
{"name": "Boltzmann Constant", "value": "1.38065 × 10⁻²³ J K⁻¹"},
{"name": "Electron Charge", "value": "1.602176 × 10⁻¹⁹ C"},
{"name": "Standard gravity", "value": "9.80665 m s⁻²"},
{"name": "Rydberg Constant", "value": "1.097373 × 10⁷ m⁻¹"},
{"name": "Planck's Constant", "value": "6.62607 × 10⁻³⁴ J S"}
],
"footer": {"text": "Use 'c!suggestion' to suggest more constants!"}
})
await ctx.send(embed=constants)
except Exception as e:
await ctx.send(embed=discord.Embed.from_dict({"title": "Error",
"description": "Something went wrong..."}))
with open("data/error_log.txt", "a") as file:
file.write(f"[Constants]: {e}\n")
def setup(client):
client.add_cog(Commands(client)) | 0.563018 | 0.397675 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence, pad_packed_sequence
from typing import Tuple, Union, Callable
class Embedding(nn.Module):
"""Embedding class"""
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int = 1, permuting: bool = True,
tracking: bool = True) -> None:
"""Instantiating Embedding class
Args:
num_embeddings (int): the number of vocabulary size
embedding_dim (int): the dimension of embedding vector
padding_idx (int): denote padding_idx to "<pad>" token
permuting (bool): permuting (n, l, c) -> (n, c, l). Default: True
tracking (bool): tracking length of sequence. Default: True
"""
super(Embedding, self).__init__()
self._tracking = tracking
self._permuting = permuting
self._padding_idx = padding_idx
self._ops = nn.Embedding(num_embeddings, embedding_dim, self._padding_idx)
def forward(self, x: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
fmap = self._ops(x).permute(0, 2, 1) if self._permuting else self._ops(x)
if self._tracking:
fmap_length = x.ne(self._padding_idx).sum(dim=1)
return fmap, fmap_length
else:
return fmap
class MaxPool1d(nn.Module):
"""MaxPool1d class"""
def __init__(self, kernel_size: int, stride: int, tracking: bool = True) -> None:
"""Instantiating MaxPool1d class
Args:
kernel_size (int): the kernel size of 1d max pooling
stride (int): the stride of 1d max pooling
tracking (bool): tracking length of sequence. Default: True
"""
super(MaxPool1d, self).__init__()
self._kernel_size = kernel_size
self._stride = stride
self._tracking = tracking
self._ops = nn.MaxPool1d(self._kernel_size, self._stride)
def forward(self, x: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) \
-> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
if self._tracking:
fmap, fmap_length = x
fmap = self._ops(fmap)
fmap_length = (fmap_length - (self._kernel_size - 1) - 1) / self._stride + 1
return fmap, fmap_length
else:
fmap = self._ops(x)
return fmap
class Conv1d(nn.Module):
"""Conv1d class"""
def __init__(self, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, padding: int = 1,
activation: Callable[[torch.Tensor], torch.Tensor] = F.relu, tracking: bool = True) -> None:
"""Instantiating Conv1d class
Args:
in_channels (int): the number of channels in the input feature map
out_channels (int): the number of channels in the output feature emap
kernel_size (int): the size of the convolving kernel
stride (int): stride of the convolution. Default: 1
padding (int): zero-padding added to both sides of the input. Default: 1
activation (function): activation function. Default: F.relu
tracking (bool): tracking length of sequence. Default: True
"""
super(Conv1d, self).__init__()
self._kernel_size = kernel_size
self._stride = stride
self._padding = padding
self._ops = nn.Conv1d(in_channels, out_channels, kernel_size, stride, padding)
self._activation = activation
self._tracking = tracking
def forward(self, x: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) \
-> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
if self._tracking:
fmap, fmap_length = x
fmap_length = (fmap_length + 2 * self._padding - (self._kernel_size - 1) - 1) / self._stride + 1
fmap = self._activation(self._ops(fmap)) if self._activation is not None else self._ops(fmap)
return fmap, fmap_length
else:
fmap = self._activation(self._ops(x)) if self._activation is not None else self._ops(x)
return fmap
class Linker(nn.Module):
"""Linker class"""
def __init__(self, permuting: bool = True) -> None:
"""Instantiating Linker class
Args:
permuting (bool): permuting (n, c, l) -> (n, l, c). Default: True
"""
super(Linker, self).__init__()
self._permuting = permuting
def forward(self, x: Tuple[torch.Tensor, torch.Tensor]) -> PackedSequence:
fmap, fmap_length = x
fmap = fmap.permute(0, 2, 1) if self._permuting else fmap
return pack_padded_sequence(fmap, fmap_length, batch_first=True, enforce_sorted=False)
class BiLSTM(nn.Module):
"""BiLSTM class"""
def __init__(self, input_size: int, hidden_size: int, using_sequence: bool = True) -> None:
"""Instantiating BiLSTM class""
Args:
input_size (int): the number of expected features in the input x
hidden_size (int): the number of features in the hidden state h
using_sequence (bool): using all hidden states of sequence. Default: True
"""
super(BiLSTM, self).__init__()
self._using_sequence = using_sequence
self._ops = nn.LSTM(input_size, hidden_size, batch_first=True, bidirectional=True)
def forward(self, x: PackedSequence) -> torch.Tensor:
outputs, hc = self._ops(x)
if self._using_sequence:
hiddens = pad_packed_sequence(outputs)[0].permute(1, 0, 2)
return hiddens
else:
feature = torch.cat([*hc[0]], dim=1)
return feature | Efficient_Character-level_Document_Classification_by_Combining_Convolution_and_Recurrent_Layers/model/ops.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence, pad_packed_sequence
from typing import Tuple, Union, Callable
class Embedding(nn.Module):
"""Embedding class"""
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int = 1, permuting: bool = True,
tracking: bool = True) -> None:
"""Instantiating Embedding class
Args:
num_embeddings (int): the number of vocabulary size
embedding_dim (int): the dimension of embedding vector
padding_idx (int): denote padding_idx to "<pad>" token
permuting (bool): permuting (n, l, c) -> (n, c, l). Default: True
tracking (bool): tracking length of sequence. Default: True
"""
super(Embedding, self).__init__()
self._tracking = tracking
self._permuting = permuting
self._padding_idx = padding_idx
self._ops = nn.Embedding(num_embeddings, embedding_dim, self._padding_idx)
def forward(self, x: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
fmap = self._ops(x).permute(0, 2, 1) if self._permuting else self._ops(x)
if self._tracking:
fmap_length = x.ne(self._padding_idx).sum(dim=1)
return fmap, fmap_length
else:
return fmap
class MaxPool1d(nn.Module):
"""MaxPool1d class"""
def __init__(self, kernel_size: int, stride: int, tracking: bool = True) -> None:
"""Instantiating MaxPool1d class
Args:
kernel_size (int): the kernel size of 1d max pooling
stride (int): the stride of 1d max pooling
tracking (bool): tracking length of sequence. Default: True
"""
super(MaxPool1d, self).__init__()
self._kernel_size = kernel_size
self._stride = stride
self._tracking = tracking
self._ops = nn.MaxPool1d(self._kernel_size, self._stride)
def forward(self, x: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) \
-> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
if self._tracking:
fmap, fmap_length = x
fmap = self._ops(fmap)
fmap_length = (fmap_length - (self._kernel_size - 1) - 1) / self._stride + 1
return fmap, fmap_length
else:
fmap = self._ops(x)
return fmap
class Conv1d(nn.Module):
"""Conv1d class"""
def __init__(self, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, padding: int = 1,
activation: Callable[[torch.Tensor], torch.Tensor] = F.relu, tracking: bool = True) -> None:
"""Instantiating Conv1d class
Args:
in_channels (int): the number of channels in the input feature map
out_channels (int): the number of channels in the output feature emap
kernel_size (int): the size of the convolving kernel
stride (int): stride of the convolution. Default: 1
padding (int): zero-padding added to both sides of the input. Default: 1
activation (function): activation function. Default: F.relu
tracking (bool): tracking length of sequence. Default: True
"""
super(Conv1d, self).__init__()
self._kernel_size = kernel_size
self._stride = stride
self._padding = padding
self._ops = nn.Conv1d(in_channels, out_channels, kernel_size, stride, padding)
self._activation = activation
self._tracking = tracking
def forward(self, x: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) \
-> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
if self._tracking:
fmap, fmap_length = x
fmap_length = (fmap_length + 2 * self._padding - (self._kernel_size - 1) - 1) / self._stride + 1
fmap = self._activation(self._ops(fmap)) if self._activation is not None else self._ops(fmap)
return fmap, fmap_length
else:
fmap = self._activation(self._ops(x)) if self._activation is not None else self._ops(x)
return fmap
class Linker(nn.Module):
"""Linker class"""
def __init__(self, permuting: bool = True) -> None:
"""Instantiating Linker class
Args:
permuting (bool): permuting (n, c, l) -> (n, l, c). Default: True
"""
super(Linker, self).__init__()
self._permuting = permuting
def forward(self, x: Tuple[torch.Tensor, torch.Tensor]) -> PackedSequence:
fmap, fmap_length = x
fmap = fmap.permute(0, 2, 1) if self._permuting else fmap
return pack_padded_sequence(fmap, fmap_length, batch_first=True, enforce_sorted=False)
class BiLSTM(nn.Module):
"""BiLSTM class"""
def __init__(self, input_size: int, hidden_size: int, using_sequence: bool = True) -> None:
"""Instantiating BiLSTM class""
Args:
input_size (int): the number of expected features in the input x
hidden_size (int): the number of features in the hidden state h
using_sequence (bool): using all hidden states of sequence. Default: True
"""
super(BiLSTM, self).__init__()
self._using_sequence = using_sequence
self._ops = nn.LSTM(input_size, hidden_size, batch_first=True, bidirectional=True)
def forward(self, x: PackedSequence) -> torch.Tensor:
outputs, hc = self._ops(x)
if self._using_sequence:
hiddens = pad_packed_sequence(outputs)[0].permute(1, 0, 2)
return hiddens
else:
feature = torch.cat([*hc[0]], dim=1)
return feature | 0.975414 | 0.596991 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = [
'ShardingInstanceMongoListArgs',
'ShardingInstanceShardListArgs',
]
@pulumi.input_type
class ShardingInstanceMongoListArgs:
def __init__(__self__, *,
node_class: pulumi.Input[str],
connect_string: Optional[pulumi.Input[str]] = None,
node_id: Optional[pulumi.Input[str]] = None,
port: Optional[pulumi.Input[int]] = None):
"""
:param pulumi.Input[str] node_class: -(Required) Node specification. see [Instance specifications](https://www.alibabacloud.com/help/doc-detail/57141.htm).
:param pulumi.Input[str] connect_string: Mongo node connection string
:param pulumi.Input[str] node_id: The ID of the shard-node.
:param pulumi.Input[int] port: Mongo node port
* `shard_list`
"""
pulumi.set(__self__, "node_class", node_class)
if connect_string is not None:
pulumi.set(__self__, "connect_string", connect_string)
if node_id is not None:
pulumi.set(__self__, "node_id", node_id)
if port is not None:
pulumi.set(__self__, "port", port)
@property
@pulumi.getter(name="nodeClass")
def node_class(self) -> pulumi.Input[str]:
"""
-(Required) Node specification. see [Instance specifications](https://www.alibabacloud.com/help/doc-detail/57141.htm).
"""
return pulumi.get(self, "node_class")
@node_class.setter
def node_class(self, value: pulumi.Input[str]):
pulumi.set(self, "node_class", value)
@property
@pulumi.getter(name="connectString")
def connect_string(self) -> Optional[pulumi.Input[str]]:
"""
Mongo node connection string
"""
return pulumi.get(self, "connect_string")
@connect_string.setter
def connect_string(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "connect_string", value)
@property
@pulumi.getter(name="nodeId")
def node_id(self) -> Optional[pulumi.Input[str]]:
"""
The ID of the shard-node.
"""
return pulumi.get(self, "node_id")
@node_id.setter
def node_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "node_id", value)
@property
@pulumi.getter
def port(self) -> Optional[pulumi.Input[int]]:
"""
Mongo node port
* `shard_list`
"""
return pulumi.get(self, "port")
@port.setter
def port(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "port", value)
@pulumi.input_type
class ShardingInstanceShardListArgs:
def __init__(__self__, *,
node_class: pulumi.Input[str],
node_storage: pulumi.Input[int],
node_id: Optional[pulumi.Input[str]] = None,
readonly_replicas: Optional[pulumi.Input[int]] = None):
"""
:param pulumi.Input[str] node_class: -(Required) Node specification. see [Instance specifications](https://www.alibabacloud.com/help/doc-detail/57141.htm).
:param pulumi.Input[int] node_storage: - Custom storage space; value range: [10, 1,000]
- 10-GB increments. Unit: GB.
:param pulumi.Input[str] node_id: The ID of the shard-node.
:param pulumi.Input[int] readonly_replicas: The number of read-only nodes in shard node. Valid values: 0 to 5. Default value: 0.
"""
pulumi.set(__self__, "node_class", node_class)
pulumi.set(__self__, "node_storage", node_storage)
if node_id is not None:
pulumi.set(__self__, "node_id", node_id)
if readonly_replicas is not None:
pulumi.set(__self__, "readonly_replicas", readonly_replicas)
@property
@pulumi.getter(name="nodeClass")
def node_class(self) -> pulumi.Input[str]:
"""
-(Required) Node specification. see [Instance specifications](https://www.alibabacloud.com/help/doc-detail/57141.htm).
"""
return pulumi.get(self, "node_class")
@node_class.setter
def node_class(self, value: pulumi.Input[str]):
pulumi.set(self, "node_class", value)
@property
@pulumi.getter(name="nodeStorage")
def node_storage(self) -> pulumi.Input[int]:
"""
- Custom storage space; value range: [10, 1,000]
- 10-GB increments. Unit: GB.
"""
return pulumi.get(self, "node_storage")
@node_storage.setter
def node_storage(self, value: pulumi.Input[int]):
pulumi.set(self, "node_storage", value)
@property
@pulumi.getter(name="nodeId")
def node_id(self) -> Optional[pulumi.Input[str]]:
"""
The ID of the shard-node.
"""
return pulumi.get(self, "node_id")
@node_id.setter
def node_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "node_id", value)
@property
@pulumi.getter(name="readonlyReplicas")
def readonly_replicas(self) -> Optional[pulumi.Input[int]]:
"""
The number of read-only nodes in shard node. Valid values: 0 to 5. Default value: 0.
"""
return pulumi.get(self, "readonly_replicas")
@readonly_replicas.setter
def readonly_replicas(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "readonly_replicas", value) | sdk/python/pulumi_alicloud/mongodb/_inputs.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = [
'ShardingInstanceMongoListArgs',
'ShardingInstanceShardListArgs',
]
@pulumi.input_type
class ShardingInstanceMongoListArgs:
def __init__(__self__, *,
node_class: pulumi.Input[str],
connect_string: Optional[pulumi.Input[str]] = None,
node_id: Optional[pulumi.Input[str]] = None,
port: Optional[pulumi.Input[int]] = None):
"""
:param pulumi.Input[str] node_class: -(Required) Node specification. see [Instance specifications](https://www.alibabacloud.com/help/doc-detail/57141.htm).
:param pulumi.Input[str] connect_string: Mongo node connection string
:param pulumi.Input[str] node_id: The ID of the shard-node.
:param pulumi.Input[int] port: Mongo node port
* `shard_list`
"""
pulumi.set(__self__, "node_class", node_class)
if connect_string is not None:
pulumi.set(__self__, "connect_string", connect_string)
if node_id is not None:
pulumi.set(__self__, "node_id", node_id)
if port is not None:
pulumi.set(__self__, "port", port)
@property
@pulumi.getter(name="nodeClass")
def node_class(self) -> pulumi.Input[str]:
"""
-(Required) Node specification. see [Instance specifications](https://www.alibabacloud.com/help/doc-detail/57141.htm).
"""
return pulumi.get(self, "node_class")
@node_class.setter
def node_class(self, value: pulumi.Input[str]):
pulumi.set(self, "node_class", value)
@property
@pulumi.getter(name="connectString")
def connect_string(self) -> Optional[pulumi.Input[str]]:
"""
Mongo node connection string
"""
return pulumi.get(self, "connect_string")
@connect_string.setter
def connect_string(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "connect_string", value)
@property
@pulumi.getter(name="nodeId")
def node_id(self) -> Optional[pulumi.Input[str]]:
"""
The ID of the shard-node.
"""
return pulumi.get(self, "node_id")
@node_id.setter
def node_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "node_id", value)
@property
@pulumi.getter
def port(self) -> Optional[pulumi.Input[int]]:
"""
Mongo node port
* `shard_list`
"""
return pulumi.get(self, "port")
@port.setter
def port(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "port", value)
@pulumi.input_type
class ShardingInstanceShardListArgs:
def __init__(__self__, *,
node_class: pulumi.Input[str],
node_storage: pulumi.Input[int],
node_id: Optional[pulumi.Input[str]] = None,
readonly_replicas: Optional[pulumi.Input[int]] = None):
"""
:param pulumi.Input[str] node_class: -(Required) Node specification. see [Instance specifications](https://www.alibabacloud.com/help/doc-detail/57141.htm).
:param pulumi.Input[int] node_storage: - Custom storage space; value range: [10, 1,000]
- 10-GB increments. Unit: GB.
:param pulumi.Input[str] node_id: The ID of the shard-node.
:param pulumi.Input[int] readonly_replicas: The number of read-only nodes in shard node. Valid values: 0 to 5. Default value: 0.
"""
pulumi.set(__self__, "node_class", node_class)
pulumi.set(__self__, "node_storage", node_storage)
if node_id is not None:
pulumi.set(__self__, "node_id", node_id)
if readonly_replicas is not None:
pulumi.set(__self__, "readonly_replicas", readonly_replicas)
@property
@pulumi.getter(name="nodeClass")
def node_class(self) -> pulumi.Input[str]:
"""
-(Required) Node specification. see [Instance specifications](https://www.alibabacloud.com/help/doc-detail/57141.htm).
"""
return pulumi.get(self, "node_class")
@node_class.setter
def node_class(self, value: pulumi.Input[str]):
pulumi.set(self, "node_class", value)
@property
@pulumi.getter(name="nodeStorage")
def node_storage(self) -> pulumi.Input[int]:
"""
- Custom storage space; value range: [10, 1,000]
- 10-GB increments. Unit: GB.
"""
return pulumi.get(self, "node_storage")
@node_storage.setter
def node_storage(self, value: pulumi.Input[int]):
pulumi.set(self, "node_storage", value)
@property
@pulumi.getter(name="nodeId")
def node_id(self) -> Optional[pulumi.Input[str]]:
"""
The ID of the shard-node.
"""
return pulumi.get(self, "node_id")
@node_id.setter
def node_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "node_id", value)
@property
@pulumi.getter(name="readonlyReplicas")
def readonly_replicas(self) -> Optional[pulumi.Input[int]]:
"""
The number of read-only nodes in shard node. Valid values: 0 to 5. Default value: 0.
"""
return pulumi.get(self, "readonly_replicas")
@readonly_replicas.setter
def readonly_replicas(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "readonly_replicas", value) | 0.822153 | 0.116036 |
from tkinter import *
janela = Tk()
janela.title('Calculadora Simples')
e = Entry(janela, width=35, bg='white', borderwidth=5)
e.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
# e.insert(0, 'Enter your name: ')
def criar_botao(numero):
atual = e.get()
e.delete(0, END)
e.insert(0, str(atual) + str(numero))
def botao_limpar():
e.delete(0, END)
def botao_igual():
segundo_numero = e.get()
e.delete(0, END)
if operacao == 'adição':
e.insert(0, f_num + int(segundo_numero))
if operacao == 'subtração':
e.insert(0, f_num - int(segundo_numero))
if operacao == 'multiplicação':
e.insert(0, f_num * int(segundo_numero))
if operacao == 'divisão':
e.insert(0, f_num / int(segundo_numero))
def botao_adicao():
primeiro_numero = e.get()
global f_num
global operacao
operacao = 'adição'
f_num = int(primeiro_numero)
e.delete(0, END)
def botao_subtracao():
primeiro_numero = e.get()
global f_num
global operacao
operacao = 'subtracão'
f_num = int(primeiro_numero)
e.delete(0, END)
def botao_multiplicacao():
primeiro_numero = e.get()
global f_num
global operacao
operacao = 'multiplicação'
f_num = int(primeiro_numero)
e.delete(0, END)
def botao_divisao():
first_number = e.get()
global f_num
global operacao
operacao = 'divisão'
f_num = int(first_number)
e.delete(0, END)
# Definir botoes
button_1 = Button(janela, text='1', padx=40, pady=20, command=lambda: criar_botao(1))
button_2 = Button(janela, text='2', padx=40, pady=20, command=lambda: criar_botao(2))
button_3 = Button(janela, text='3', padx=40, pady=20, command=lambda: criar_botao(3))
button_4 = Button(janela, text='4', padx=40, pady=20, command=lambda: criar_botao(4))
button_5 = Button(janela, text='5', padx=40, pady=20, command=lambda: criar_botao(5))
button_6 = Button(janela, text='6', padx=40, pady=20, command=lambda: criar_botao(6))
button_7 = Button(janela, text='7', padx=40, pady=20, command=lambda: criar_botao(7))
button_8 = Button(janela, text='8', padx=40, pady=20, command=lambda: criar_botao(8))
button_9 = Button(janela, text='9', padx=40, pady=20, command=lambda: criar_botao(9))
button_0 = Button(janela, text='0', padx=40, pady=20, command=lambda: criar_botao(0))
button_ad = Button(janela, text='+', padx=38, pady=20, command=botao_adicao)
button_subtract = Button(janela, text='-', padx=40, pady=20, command=botao_subtracao)
button_multiply = Button(janela, text='x', padx=40, pady=20, command=botao_multiplicacao)
button_divide = Button(janela, text='/', padx=40, pady=20, command=botao_divisao)
button_equal = Button(janela, text='=', padx=88, pady=20, command=botao_igual)
button_clear = Button(janela, text='Clear', padx=80, pady=20, command=botao_limpar)
#Colocar na tela
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)
button_0.grid(row=4, column=0)
button_clear.grid(row=5, column=1, columnspan=2)
button_ad.grid(row=4, column=3)
button_subtract.grid(row=3, column=3)
button_multiply.grid(row=1, column=3)
button_divide.grid(row=2, column=3)
button_equal.grid(row=4, column=1, columnspan=2)
janela.mainloop() | Calculadora.py | from tkinter import *
janela = Tk()
janela.title('Calculadora Simples')
e = Entry(janela, width=35, bg='white', borderwidth=5)
e.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
# e.insert(0, 'Enter your name: ')
def criar_botao(numero):
atual = e.get()
e.delete(0, END)
e.insert(0, str(atual) + str(numero))
def botao_limpar():
e.delete(0, END)
def botao_igual():
segundo_numero = e.get()
e.delete(0, END)
if operacao == 'adição':
e.insert(0, f_num + int(segundo_numero))
if operacao == 'subtração':
e.insert(0, f_num - int(segundo_numero))
if operacao == 'multiplicação':
e.insert(0, f_num * int(segundo_numero))
if operacao == 'divisão':
e.insert(0, f_num / int(segundo_numero))
def botao_adicao():
primeiro_numero = e.get()
global f_num
global operacao
operacao = 'adição'
f_num = int(primeiro_numero)
e.delete(0, END)
def botao_subtracao():
primeiro_numero = e.get()
global f_num
global operacao
operacao = 'subtracão'
f_num = int(primeiro_numero)
e.delete(0, END)
def botao_multiplicacao():
primeiro_numero = e.get()
global f_num
global operacao
operacao = 'multiplicação'
f_num = int(primeiro_numero)
e.delete(0, END)
def botao_divisao():
first_number = e.get()
global f_num
global operacao
operacao = 'divisão'
f_num = int(first_number)
e.delete(0, END)
# Definir botoes
button_1 = Button(janela, text='1', padx=40, pady=20, command=lambda: criar_botao(1))
button_2 = Button(janela, text='2', padx=40, pady=20, command=lambda: criar_botao(2))
button_3 = Button(janela, text='3', padx=40, pady=20, command=lambda: criar_botao(3))
button_4 = Button(janela, text='4', padx=40, pady=20, command=lambda: criar_botao(4))
button_5 = Button(janela, text='5', padx=40, pady=20, command=lambda: criar_botao(5))
button_6 = Button(janela, text='6', padx=40, pady=20, command=lambda: criar_botao(6))
button_7 = Button(janela, text='7', padx=40, pady=20, command=lambda: criar_botao(7))
button_8 = Button(janela, text='8', padx=40, pady=20, command=lambda: criar_botao(8))
button_9 = Button(janela, text='9', padx=40, pady=20, command=lambda: criar_botao(9))
button_0 = Button(janela, text='0', padx=40, pady=20, command=lambda: criar_botao(0))
button_ad = Button(janela, text='+', padx=38, pady=20, command=botao_adicao)
button_subtract = Button(janela, text='-', padx=40, pady=20, command=botao_subtracao)
button_multiply = Button(janela, text='x', padx=40, pady=20, command=botao_multiplicacao)
button_divide = Button(janela, text='/', padx=40, pady=20, command=botao_divisao)
button_equal = Button(janela, text='=', padx=88, pady=20, command=botao_igual)
button_clear = Button(janela, text='Clear', padx=80, pady=20, command=botao_limpar)
#Colocar na tela
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)
button_0.grid(row=4, column=0)
button_clear.grid(row=5, column=1, columnspan=2)
button_ad.grid(row=4, column=3)
button_subtract.grid(row=3, column=3)
button_multiply.grid(row=1, column=3)
button_divide.grid(row=2, column=3)
button_equal.grid(row=4, column=1, columnspan=2)
janela.mainloop() | 0.313945 | 0.142799 |
import queue
import threading
from lib.api.api import InternalException
from lib.socket_wrapper import Connect
from owner import Owner
class SubscriptionsWorker(threading.Thread):
def __init__(self, own: Owner, conn: Connect):
super().__init__()
self.own = own
self._conn = conn
self._queue = queue.Queue()
self._subscribes = set()
self.work = True
self.start()
def run(self) -> None:
while self.work:
notify = self._queue.get()
if notify is None:
break
elif self._conn.alive:
name, args, kwargs = _send_adapter(*notify)
msg = {'method': 'notify.{}'.format(name), 'params': {'args': args, 'kwargs': kwargs}}
self._conn.write(msg)
else:
break
self._unsubscribe_all()
def _new_message(self, name, *args, **kwargs):
if self.work:
self._queue.put_nowait((name, args, kwargs))
def _unsubscribe_all(self):
self.work = False
if self._subscribes:
self.own.unsubscribe(list(self._subscribes), self._new_message)
self._subscribes.clear()
def close_signal(self):
self._queue.put_nowait(None)
self.work = False
def join(self, timeout=5):
self.close_signal()
super().join(timeout)
def subscribe(self, data: list) -> bool:
if not self.work:
return False
data = _sanitize_subscribe_list(data) - self._subscribes
self._subscribes.update(data)
return self.own.subscribe(list(data), self._new_message)
def unsubscribe(self, data: list) -> bool:
if not self.work:
return False
data = _sanitize_subscribe_list(data) & self._subscribes
self._subscribes.difference_update(data)
return self.own.unsubscribe(list(data), self._new_message)
def events_list(self) -> list:
return _send_list_adapter(self.own.events_list()) if self.work else []
def _sanitize_subscribe_list(data: list) -> set:
if not data or not isinstance(data, list) or any(True for el in data if not isinstance(el, str) or el == ''):
raise InternalException(msg='params must be non-empty list<str>')
return _receive_adapter(set(data))
_ADAPTER_SEND_MAP = {
'start_talking': ('talking', True),
'stop_talking': ('talking', False),
'start_record': ('record', True),
'stop_record': ('record', False),
'start_stt_event': ('stt_event', True),
'stop_stt_event': ('stt_event', False),
}
_ADAPTER_RECEIVE_MAP = {}
def __make():
for key, (val, _) in _ADAPTER_SEND_MAP.items():
if val not in _ADAPTER_RECEIVE_MAP:
_ADAPTER_RECEIVE_MAP[val] = set()
_ADAPTER_RECEIVE_MAP[val].add(key)
__make()
def _receive_adapter(subscriptions: set) -> set:
for key in list(subscriptions):
if key in _ADAPTER_RECEIVE_MAP:
subscriptions.discard(key)
subscriptions.update(_ADAPTER_RECEIVE_MAP[key])
return subscriptions
def _send_list_adapter(events: list) -> list:
return list({_ADAPTER_SEND_MAP.get(key, (key,))[0] for key in events})
def _send_adapter(name, args, kwargs) -> tuple:
if name in _ADAPTER_SEND_MAP:
args = [_ADAPTER_SEND_MAP[name][1]]
name = _ADAPTER_SEND_MAP[name][0]
elif name == 'listener' and args:
args = [args[0] == 'on']
return name, args, kwargs | src/lib/subscriptions_worker.py | import queue
import threading
from lib.api.api import InternalException
from lib.socket_wrapper import Connect
from owner import Owner
class SubscriptionsWorker(threading.Thread):
def __init__(self, own: Owner, conn: Connect):
super().__init__()
self.own = own
self._conn = conn
self._queue = queue.Queue()
self._subscribes = set()
self.work = True
self.start()
def run(self) -> None:
while self.work:
notify = self._queue.get()
if notify is None:
break
elif self._conn.alive:
name, args, kwargs = _send_adapter(*notify)
msg = {'method': 'notify.{}'.format(name), 'params': {'args': args, 'kwargs': kwargs}}
self._conn.write(msg)
else:
break
self._unsubscribe_all()
def _new_message(self, name, *args, **kwargs):
if self.work:
self._queue.put_nowait((name, args, kwargs))
def _unsubscribe_all(self):
self.work = False
if self._subscribes:
self.own.unsubscribe(list(self._subscribes), self._new_message)
self._subscribes.clear()
def close_signal(self):
self._queue.put_nowait(None)
self.work = False
def join(self, timeout=5):
self.close_signal()
super().join(timeout)
def subscribe(self, data: list) -> bool:
if not self.work:
return False
data = _sanitize_subscribe_list(data) - self._subscribes
self._subscribes.update(data)
return self.own.subscribe(list(data), self._new_message)
def unsubscribe(self, data: list) -> bool:
if not self.work:
return False
data = _sanitize_subscribe_list(data) & self._subscribes
self._subscribes.difference_update(data)
return self.own.unsubscribe(list(data), self._new_message)
def events_list(self) -> list:
return _send_list_adapter(self.own.events_list()) if self.work else []
def _sanitize_subscribe_list(data: list) -> set:
if not data or not isinstance(data, list) or any(True for el in data if not isinstance(el, str) or el == ''):
raise InternalException(msg='params must be non-empty list<str>')
return _receive_adapter(set(data))
_ADAPTER_SEND_MAP = {
'start_talking': ('talking', True),
'stop_talking': ('talking', False),
'start_record': ('record', True),
'stop_record': ('record', False),
'start_stt_event': ('stt_event', True),
'stop_stt_event': ('stt_event', False),
}
_ADAPTER_RECEIVE_MAP = {}
def __make():
for key, (val, _) in _ADAPTER_SEND_MAP.items():
if val not in _ADAPTER_RECEIVE_MAP:
_ADAPTER_RECEIVE_MAP[val] = set()
_ADAPTER_RECEIVE_MAP[val].add(key)
__make()
def _receive_adapter(subscriptions: set) -> set:
for key in list(subscriptions):
if key in _ADAPTER_RECEIVE_MAP:
subscriptions.discard(key)
subscriptions.update(_ADAPTER_RECEIVE_MAP[key])
return subscriptions
def _send_list_adapter(events: list) -> list:
return list({_ADAPTER_SEND_MAP.get(key, (key,))[0] for key in events})
def _send_adapter(name, args, kwargs) -> tuple:
if name in _ADAPTER_SEND_MAP:
args = [_ADAPTER_SEND_MAP[name][1]]
name = _ADAPTER_SEND_MAP[name][0]
elif name == 'listener' and args:
args = [args[0] == 'on']
return name, args, kwargs | 0.379953 | 0.080141 |
from pathlib import Path
import datetime
import pytube
import os
class VideoDownloader:
def __init__(self, request_body=None, video_id=None):
self.__body = request_body
self.__url = f'https://www.youtube.com/watch?v={video_id}'
self.__youtube = pytube.YouTube(self.__url)
self.__file_name = None
self.__storage_path = Path(__file__).parents[1].joinpath('storage')
self.__storage_helper()
def __storage_helper(self):
for f in os.listdir(self.__storage_path):
os.remove(os.path.join(self.__storage_path, f))
def __get_file_info(self):
return {'title': self.__youtube.title,
'author': self.__youtube.author,
'description': self.__youtube.description,
'duration': datetime.timedelta(seconds=self.__youtube.length),
'file_name': self.__file_name,
'download_path': str(self.__storage_path.joinpath(self.__file_name))
}
def __get_file_name(self):
file_name = str(self.__youtube.title)
remove_characters = ['/', '\\', '|', '*', '?', ':', '<', '>', '"']
for c in remove_characters:
file_name = file_name.replace(c, '')
self.__file_name = file_name
def __download(self, video=None, audio=None):
file = None
self.__get_file_name()
if video is not None:
file_extension = 'mp4'
file = video
self.__file_name = f'{self.__file_name}({video.resolution}).{file_extension}'
if audio is not None:
file_extension = 'mp3'
file = audio
self.__file_name = f'{self.__file_name}.{file_extension}'
file.download(str(self.__storage_path), filename=self.__file_name)
def get_file(self):
if self.__body['extension'] == 'mp3':
self.__download(audio=self.__youtube.streams.get_audio_only())
if self.__body['extension'] == 'mp4':
if self.__body['quality'] == 'baixa':
self.__download(video=self.__youtube.streams.get_lowest_resolution())
if self.__body['quality'] == 'alta':
self.__download(video=self.__youtube.streams.get_highest_resolution())
return self.__get_file_info()
def get_video_by_resolution(self, resolution):
self.__download(video=self.__youtube.streams.get_by_resolution(resolution=resolution))
return self.__get_file_info()
def get_video_highest_resolution(self):
self.__download(video=self.__youtube.streams.get_highest_resolution())
return self.__get_file_info()
def get_video_lowest_resolution(self):
self.__download(video=self.__youtube.streams.get_lowest_resolution())
return self.__get_file_info()
def get_only_audio(self):
self.__download(audio=self.__youtube.streams.get_audio_only())
return self.__get_file_info() | baixatube-service/utils/downloader_utils.py | from pathlib import Path
import datetime
import pytube
import os
class VideoDownloader:
def __init__(self, request_body=None, video_id=None):
self.__body = request_body
self.__url = f'https://www.youtube.com/watch?v={video_id}'
self.__youtube = pytube.YouTube(self.__url)
self.__file_name = None
self.__storage_path = Path(__file__).parents[1].joinpath('storage')
self.__storage_helper()
def __storage_helper(self):
for f in os.listdir(self.__storage_path):
os.remove(os.path.join(self.__storage_path, f))
def __get_file_info(self):
return {'title': self.__youtube.title,
'author': self.__youtube.author,
'description': self.__youtube.description,
'duration': datetime.timedelta(seconds=self.__youtube.length),
'file_name': self.__file_name,
'download_path': str(self.__storage_path.joinpath(self.__file_name))
}
def __get_file_name(self):
file_name = str(self.__youtube.title)
remove_characters = ['/', '\\', '|', '*', '?', ':', '<', '>', '"']
for c in remove_characters:
file_name = file_name.replace(c, '')
self.__file_name = file_name
def __download(self, video=None, audio=None):
file = None
self.__get_file_name()
if video is not None:
file_extension = 'mp4'
file = video
self.__file_name = f'{self.__file_name}({video.resolution}).{file_extension}'
if audio is not None:
file_extension = 'mp3'
file = audio
self.__file_name = f'{self.__file_name}.{file_extension}'
file.download(str(self.__storage_path), filename=self.__file_name)
def get_file(self):
if self.__body['extension'] == 'mp3':
self.__download(audio=self.__youtube.streams.get_audio_only())
if self.__body['extension'] == 'mp4':
if self.__body['quality'] == 'baixa':
self.__download(video=self.__youtube.streams.get_lowest_resolution())
if self.__body['quality'] == 'alta':
self.__download(video=self.__youtube.streams.get_highest_resolution())
return self.__get_file_info()
def get_video_by_resolution(self, resolution):
self.__download(video=self.__youtube.streams.get_by_resolution(resolution=resolution))
return self.__get_file_info()
def get_video_highest_resolution(self):
self.__download(video=self.__youtube.streams.get_highest_resolution())
return self.__get_file_info()
def get_video_lowest_resolution(self):
self.__download(video=self.__youtube.streams.get_lowest_resolution())
return self.__get_file_info()
def get_only_audio(self):
self.__download(audio=self.__youtube.streams.get_audio_only())
return self.__get_file_info() | 0.611034 | 0.092401 |
import os
import csv
import random
def find_unique(annotations: str) -> dict:
"""
find_unique will loop through the annotations csv, and generate a dictionary which contains
the unique images, and all associated rows. This is neccesary as the csv sometimes contains
multiple entries for an image, specifically when an image has more than 1 lesion present.
Parameters
----------
annotations : str
path to csv file containing annotations.
Returns
-------
dict
Dictionary containing unique images. Of the form
{Unique_image: [[row1],[row2],...,[rowN]]}
"""
return_dict = {}
with open(annotations, "r") as f:
reader = csv.reader(f)
next(reader)
for line in reader:
if line[0] in return_dict.keys():
return_dict[line[0]].append(line)
else:
return_dict.update({line[0]:[line]})
return return_dict
def dict_split(train: dict, test: dict, val: dict) -> list:
"""
dict_split takes in a train dictionary, that should contain all images, and two empty dictionaries
(test, and val) which should be empty. It will then iterator over train and remove 100 random negative
and 1000 random positive samples and place them in test (and likewise for val)
Additionally, it will return a list of the indexes of the keys of all the randomly selected samples
in the list removed_set. this is so that these samples may be removed from train.
Parameters
----------
train : dict
Dictionary containing all images.
test : dict
Empty dictionary that will contain test images.
val : dict
Empty dictionary that will contain val iamges.
Returns
-------
list
A list containing the index of the keys populated into the val and test dicionaries.
"""
removed_set = []
val_negative = 0
test_negative = 0
val_positive = 0
test_positive = 0
keys = list(train.keys())
random.shuffle(keys)
for idx, key in enumerate(keys):
coord_list = [int(c) for c in train[key][0][1:5]]
if all(coord_list):
if test_positive < 100:
removed_set.append(keys.index(key))
test_positive += 1
test.update({key:train[key]})
elif val_positive < 100:
removed_set.append(keys.index(key))
val_positive += 1
val.update({key:train[key]})
elif not all(coord_list):
if test_negative < 100:
removed_set.append(keys.index(key))
test_negative += 1
test.update({key:train[key]})
elif val_negative < 100:
removed_set.append(keys.index(key))
val_negative += 1
val.update({key:train[key]})
if val_positive >= 100 and test_positive >= 100 and val_negative >= 100 and test_negative >= 100:
break
return removed_set
def clean_dict(removed_set: list, dictionary: dict):
"""
clean_dict takes in a list of indexes of samples occuring in a dictionary as keys, and a dictionary
the keys appearing in removed_set will be removed from the dictionary.
Parameters
----------
removed_set : list
list of indexes of samples.
dictionary : dict
The train dict to remove from.
Returns
-------
None.
"""
removed_set.sort()
removed_set.reverse()
for key in removed_set:
key_s = list(dictionary.keys())[key]
dictionary.pop(key_s)
def write_csv(dict_annotations, file_name, orig_dir="", dest_dir=""):
with open(file_name, "w", newline='') as f:
writer = csv.writer(f)
for key in dict_annotations.keys():
if len(orig_dir):
file = os.path.join(orig_dir, key)
os.rename(file, os.path.join(dest_dir, key))
for line in dict_annotations[key]:
writer.writerow(line)
if __name__=="__main__":
base_dir = "E:\Coding\Dataset"
annotations = os.path.join(base_dir, "annotations_handheld.csv")
pic_locations = os.path.join(base_dir, "images_handheld")
test_dir = os.path.join(base_dir, "images_test")
val_dir = os.path.join(base_dir, "images_validation")
train = {}
test = {}
val = {}
train = find_unique(annotations)
removed_set = dict_split(train, test, val)
clean_dict(removed_set, train)
train_annotations = os.path.join(base_dir, "annotations_train.csv")
test_annotations = os.path.join(base_dir, "annotations_test.csv")
val_annotations = os.path.join(base_dir, "annotations_val.csv")
write_csv(train, train_annotations)
write_csv(test, test_annotations, orig_dir=pic_locations, dest_dir=test_dir)
write_csv(val, val_annotations, orig_dir=pic_locations, dest_dir=val_dir) | ML/createSplits.py | import os
import csv
import random
def find_unique(annotations: str) -> dict:
"""
find_unique will loop through the annotations csv, and generate a dictionary which contains
the unique images, and all associated rows. This is neccesary as the csv sometimes contains
multiple entries for an image, specifically when an image has more than 1 lesion present.
Parameters
----------
annotations : str
path to csv file containing annotations.
Returns
-------
dict
Dictionary containing unique images. Of the form
{Unique_image: [[row1],[row2],...,[rowN]]}
"""
return_dict = {}
with open(annotations, "r") as f:
reader = csv.reader(f)
next(reader)
for line in reader:
if line[0] in return_dict.keys():
return_dict[line[0]].append(line)
else:
return_dict.update({line[0]:[line]})
return return_dict
def dict_split(train: dict, test: dict, val: dict) -> list:
"""
dict_split takes in a train dictionary, that should contain all images, and two empty dictionaries
(test, and val) which should be empty. It will then iterator over train and remove 100 random negative
and 1000 random positive samples and place them in test (and likewise for val)
Additionally, it will return a list of the indexes of the keys of all the randomly selected samples
in the list removed_set. this is so that these samples may be removed from train.
Parameters
----------
train : dict
Dictionary containing all images.
test : dict
Empty dictionary that will contain test images.
val : dict
Empty dictionary that will contain val iamges.
Returns
-------
list
A list containing the index of the keys populated into the val and test dicionaries.
"""
removed_set = []
val_negative = 0
test_negative = 0
val_positive = 0
test_positive = 0
keys = list(train.keys())
random.shuffle(keys)
for idx, key in enumerate(keys):
coord_list = [int(c) for c in train[key][0][1:5]]
if all(coord_list):
if test_positive < 100:
removed_set.append(keys.index(key))
test_positive += 1
test.update({key:train[key]})
elif val_positive < 100:
removed_set.append(keys.index(key))
val_positive += 1
val.update({key:train[key]})
elif not all(coord_list):
if test_negative < 100:
removed_set.append(keys.index(key))
test_negative += 1
test.update({key:train[key]})
elif val_negative < 100:
removed_set.append(keys.index(key))
val_negative += 1
val.update({key:train[key]})
if val_positive >= 100 and test_positive >= 100 and val_negative >= 100 and test_negative >= 100:
break
return removed_set
def clean_dict(removed_set: list, dictionary: dict):
"""
clean_dict takes in a list of indexes of samples occuring in a dictionary as keys, and a dictionary
the keys appearing in removed_set will be removed from the dictionary.
Parameters
----------
removed_set : list
list of indexes of samples.
dictionary : dict
The train dict to remove from.
Returns
-------
None.
"""
removed_set.sort()
removed_set.reverse()
for key in removed_set:
key_s = list(dictionary.keys())[key]
dictionary.pop(key_s)
def write_csv(dict_annotations, file_name, orig_dir="", dest_dir=""):
with open(file_name, "w", newline='') as f:
writer = csv.writer(f)
for key in dict_annotations.keys():
if len(orig_dir):
file = os.path.join(orig_dir, key)
os.rename(file, os.path.join(dest_dir, key))
for line in dict_annotations[key]:
writer.writerow(line)
if __name__=="__main__":
base_dir = "E:\Coding\Dataset"
annotations = os.path.join(base_dir, "annotations_handheld.csv")
pic_locations = os.path.join(base_dir, "images_handheld")
test_dir = os.path.join(base_dir, "images_test")
val_dir = os.path.join(base_dir, "images_validation")
train = {}
test = {}
val = {}
train = find_unique(annotations)
removed_set = dict_split(train, test, val)
clean_dict(removed_set, train)
train_annotations = os.path.join(base_dir, "annotations_train.csv")
test_annotations = os.path.join(base_dir, "annotations_test.csv")
val_annotations = os.path.join(base_dir, "annotations_val.csv")
write_csv(train, train_annotations)
write_csv(test, test_annotations, orig_dir=pic_locations, dest_dir=test_dir)
write_csv(val, val_annotations, orig_dir=pic_locations, dest_dir=val_dir) | 0.718989 | 0.498901 |
from app import app
from flask import Flask, render_template, request, session, flash, redirect, url_for, g
from .forms import LoginForm
import pandas as pd
import numpy as np
import os
import glob
from nltk.corpus import stopwords
from gensim import corpora, models, similarities
import gensim
import sqlite3
dictionary = corpora.Dictionary.load('models/words.dict')
corpus = corpora.MmCorpus('models/corpus.mm')
tfidf = gensim.models.tfidfmodel.TfidfModel.load('models/tfidf_model')
lsi = gensim.models.lsimodel.LsiModel.load('models/model.lsi')
index = similarities.MatrixSimilarity.load('models/corpus.index')
corpus_tfidf = tfidf[corpus]
corpus_lsi = lsi[corpus_tfidf]
def connect_db():
return sqlite3.connect('/Users/sheldon/podcasts/test.db')
def create_df_object():
conn = sqlite3.connect('/Users/sheldon/podcasts/test.db')
df = pd.read_sql("select * from podcast",conn)
return df
df = create_df_object()
stop = set(stopwords.words('english'))
@app.route('/index')
@app.route('/', methods = ['GET','POST'])
def main():
if request.method == "POST":
query = request.form.get('search','default value')
return redirect('/search/{}'.format(query))
else:
conn = sqlite3.connect('/Users/sheldon/podcasts/test.db')
c = conn.cursor()
cur = c.execute('select "index", episode, series from podcast')
db_request = [dict(index=row[0], episode=row[1], series=row[2]) for row in cur.fetchall()]
return render_template('index.html', data=db_request)
@app.route('/login', methods=['GET','POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
flash('Login requested for OpenID="%s", remember_me="%s' % (form.openid.data, str(form.remember_me.data)))
return redirect('/index')
return render_template('login.html', title='Sign In', form=form)
@app.route('/register', methods=['GET','POST'])
def register():
form = RegistrationForm(request.form)
if request.method == 'POST' and form.validate():
user = User(form.username.data, form.email.data,
form.password.data)
db_session.add(user)
flash('Thanks for registering')
return redirect(url_for('login'))
return render_template('register.html', form=form)
@app.route('/related_podcasts/<int:podcast_id>')
def show_related_podcasts(podcast_id):
conn = sqlite3.connect('/Users/sheldon/podcasts/test.db')
c = conn.cursor()
cur = c.execute('select "index", episode, series from podcast where "index" ={}'.format(podcast_id))
db_request = [dict(index=row[0], episode=row[1], series=row[2]) for row in cur.fetchall()]
def get_related_podcasts(index):
def getKey(item):
return item[1]
corpus = corpus_lsi[index]
corpus = sorted(corpus, key=getKey, reverse=True)[0:10]
related_df = pd.DataFrame(corpus,columns=['index','score'])
final_df = pd.merge(related_df, df, on='index')[['index','episode','score','series']]
return final_df
final_df = get_related_podcasts(podcast_id)
related_podcasts = final_df['episode']
return render_template('related_podcasts.html',original_title=db_request[0]['episode'], data=related_podcasts)
@app.route('/search/<string:query>')
def show_related_podcast_query(query):
trans_query = query.lower()
trans_query = query.split()
def get_related_podcasts_query(query):
vec_box = dictionary.doc2bow(query.split())
vec_lsi = lsi[vec_box]
sims = index[vec_lsi]
sims = sorted(enumerate(sims), key=lambda item: -item[1])[0:10]
related_df = pd.DataFrame(sims,columns=['index','score'])
final_df = pd.merge(related_df, df, on='index')[['index','episode','score','series']]
return final_df
related_podcasts = get_related_podcasts_query(query)
related_podcasts = related_podcasts['episode']
return render_template('related_podcasts_to_query.html',original_query=query, data=related_podcasts) | apps/app/views.py | from app import app
from flask import Flask, render_template, request, session, flash, redirect, url_for, g
from .forms import LoginForm
import pandas as pd
import numpy as np
import os
import glob
from nltk.corpus import stopwords
from gensim import corpora, models, similarities
import gensim
import sqlite3
dictionary = corpora.Dictionary.load('models/words.dict')
corpus = corpora.MmCorpus('models/corpus.mm')
tfidf = gensim.models.tfidfmodel.TfidfModel.load('models/tfidf_model')
lsi = gensim.models.lsimodel.LsiModel.load('models/model.lsi')
index = similarities.MatrixSimilarity.load('models/corpus.index')
corpus_tfidf = tfidf[corpus]
corpus_lsi = lsi[corpus_tfidf]
def connect_db():
return sqlite3.connect('/Users/sheldon/podcasts/test.db')
def create_df_object():
conn = sqlite3.connect('/Users/sheldon/podcasts/test.db')
df = pd.read_sql("select * from podcast",conn)
return df
df = create_df_object()
stop = set(stopwords.words('english'))
@app.route('/index')
@app.route('/', methods = ['GET','POST'])
def main():
if request.method == "POST":
query = request.form.get('search','default value')
return redirect('/search/{}'.format(query))
else:
conn = sqlite3.connect('/Users/sheldon/podcasts/test.db')
c = conn.cursor()
cur = c.execute('select "index", episode, series from podcast')
db_request = [dict(index=row[0], episode=row[1], series=row[2]) for row in cur.fetchall()]
return render_template('index.html', data=db_request)
@app.route('/login', methods=['GET','POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
flash('Login requested for OpenID="%s", remember_me="%s' % (form.openid.data, str(form.remember_me.data)))
return redirect('/index')
return render_template('login.html', title='Sign In', form=form)
@app.route('/register', methods=['GET','POST'])
def register():
form = RegistrationForm(request.form)
if request.method == 'POST' and form.validate():
user = User(form.username.data, form.email.data,
form.password.data)
db_session.add(user)
flash('Thanks for registering')
return redirect(url_for('login'))
return render_template('register.html', form=form)
@app.route('/related_podcasts/<int:podcast_id>')
def show_related_podcasts(podcast_id):
conn = sqlite3.connect('/Users/sheldon/podcasts/test.db')
c = conn.cursor()
cur = c.execute('select "index", episode, series from podcast where "index" ={}'.format(podcast_id))
db_request = [dict(index=row[0], episode=row[1], series=row[2]) for row in cur.fetchall()]
def get_related_podcasts(index):
def getKey(item):
return item[1]
corpus = corpus_lsi[index]
corpus = sorted(corpus, key=getKey, reverse=True)[0:10]
related_df = pd.DataFrame(corpus,columns=['index','score'])
final_df = pd.merge(related_df, df, on='index')[['index','episode','score','series']]
return final_df
final_df = get_related_podcasts(podcast_id)
related_podcasts = final_df['episode']
return render_template('related_podcasts.html',original_title=db_request[0]['episode'], data=related_podcasts)
@app.route('/search/<string:query>')
def show_related_podcast_query(query):
trans_query = query.lower()
trans_query = query.split()
def get_related_podcasts_query(query):
vec_box = dictionary.doc2bow(query.split())
vec_lsi = lsi[vec_box]
sims = index[vec_lsi]
sims = sorted(enumerate(sims), key=lambda item: -item[1])[0:10]
related_df = pd.DataFrame(sims,columns=['index','score'])
final_df = pd.merge(related_df, df, on='index')[['index','episode','score','series']]
return final_df
related_podcasts = get_related_podcasts_query(query)
related_podcasts = related_podcasts['episode']
return render_template('related_podcasts_to_query.html',original_query=query, data=related_podcasts) | 0.29088 | 0.088741 |
from __future__ import absolute_import
from django.conf import settings
from sentry.tasks.base import instrumented_task
from sentry.utils.safe import safe_execute
@instrumented_task(
name='sentry.tasks.store.preprocess_event',
queue='events')
def preprocess_event(cache_key=None, data=None, **kwargs):
from sentry.app import cache
from sentry.plugins import plugins
from sentry.tasks.fetch_source import expand_javascript_source
if cache_key:
data = cache.get(cache_key)
logger = preprocess_event.get_logger()
if data is None:
logger.error('Data not available in preprocess_event (cache_key=%s)', cache_key)
return
project = data['project']
# TODO(dcramer): ideally we would know if data changed by default
has_changed = False
# TODO(dcramer): move js sourcemap processing into JS plugin
if settings.SENTRY_SCRAPE_JAVASCRIPT_CONTEXT and data.get('platform') == 'javascript':
try:
expand_javascript_source(data)
except Exception as e:
logger.exception(u'Error fetching javascript source: %r [%s]', data['event_id'], e)
else:
has_changed = True
for plugin in plugins.all(version=2):
for processor in (safe_execute(plugin.get_event_preprocessors) or ()):
result = safe_execute(processor, data)
if result:
data = result
has_changed = True
assert data['project'] == project, 'Project cannot be mutated by preprocessor'
if has_changed and cache_key:
cache.set(cache_key, data, 3600)
if cache_key:
data = None
save_event.delay(cache_key=cache_key, data=data)
@instrumented_task(
name='sentry.tasks.store.save_event',
queue='events')
def save_event(cache_key=None, data=None, **kwargs):
"""
Saves an event to the database.
"""
from sentry.app import cache
from sentry.event_manager import EventManager
if cache_key:
data = cache.get(cache_key)
if data is None:
return
project = data.pop('project')
try:
manager = EventManager(data)
manager.save(project)
finally:
if cache_key:
cache.delete(cache_key) | src/sentry/tasks/store.py | from __future__ import absolute_import
from django.conf import settings
from sentry.tasks.base import instrumented_task
from sentry.utils.safe import safe_execute
@instrumented_task(
name='sentry.tasks.store.preprocess_event',
queue='events')
def preprocess_event(cache_key=None, data=None, **kwargs):
from sentry.app import cache
from sentry.plugins import plugins
from sentry.tasks.fetch_source import expand_javascript_source
if cache_key:
data = cache.get(cache_key)
logger = preprocess_event.get_logger()
if data is None:
logger.error('Data not available in preprocess_event (cache_key=%s)', cache_key)
return
project = data['project']
# TODO(dcramer): ideally we would know if data changed by default
has_changed = False
# TODO(dcramer): move js sourcemap processing into JS plugin
if settings.SENTRY_SCRAPE_JAVASCRIPT_CONTEXT and data.get('platform') == 'javascript':
try:
expand_javascript_source(data)
except Exception as e:
logger.exception(u'Error fetching javascript source: %r [%s]', data['event_id'], e)
else:
has_changed = True
for plugin in plugins.all(version=2):
for processor in (safe_execute(plugin.get_event_preprocessors) or ()):
result = safe_execute(processor, data)
if result:
data = result
has_changed = True
assert data['project'] == project, 'Project cannot be mutated by preprocessor'
if has_changed and cache_key:
cache.set(cache_key, data, 3600)
if cache_key:
data = None
save_event.delay(cache_key=cache_key, data=data)
@instrumented_task(
name='sentry.tasks.store.save_event',
queue='events')
def save_event(cache_key=None, data=None, **kwargs):
"""
Saves an event to the database.
"""
from sentry.app import cache
from sentry.event_manager import EventManager
if cache_key:
data = cache.get(cache_key)
if data is None:
return
project = data.pop('project')
try:
manager = EventManager(data)
manager.save(project)
finally:
if cache_key:
cache.delete(cache_key) | 0.284377 | 0.160858 |
import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, Job
import os
import keys
import random
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
def start(bot, update):
update.message.reply_text(
'Hi {}'.format(update.message.from_user.first_name))
schedule_keyboard = [['Once a day', 'Twice a day'],
['Once a week', 'Never']]
reply_markup = telegram.ReplyKeyboardMarkup(schedule_keyboard,
one_time_keyboard=True)
bot.send_message(chat_id=update.message.chat_id,
text="Choose a turtle delivery frequency",
reply_markup=reply_markup)
def stop(bot, update):
jobs[update.message.chat_id].schedule_removal()
bot.send_message(chat_id=update.message.chat_id,
text="Turtle delivered stopped")
def turtle(bot, update):
print "turtle"
send_turtle(bot, update.message.chat_id)
def send_turtle(bot, c_id):
bot.send_chat_action(chat_id=c_id,
action=telegram.ChatAction.TYPING)
turtle_photos = os.listdir('turtles')
rand_turtle = turtle_photos[random.randint(0, len(turtle_photos)-1)]
if '.gif' in rand_turtle:
print "gif"
bot.send_document(chat_id=c_id,
document=open('turtles/{}'.format(rand_turtle)))
else:
bot.send_photo(chat_id=c_id,
photo=open('turtles/{}'.format(rand_turtle)))
def turtle_callback(bot, job):
send_turtle(bot, job.context)
def parse_message_response(bot, update, job_queue):
print "test"
chat_id = update.message.chat_id
user_response = update.message.text.lower()
if user_response == "fast":
job = Job(turtle_callback, 10.0, context=chat_id)
jobs[chat_id] = job
jq.put(job, next_t=0.0)
elif user_response == "once a day":
job = Job(turtle_callback, 60*60*24, context=chat_id)
jobs[chat_id] = job
jq.put(job, next_t=0.0)
elif user_response == "twice a day":
job = Job(turtle_callback, 60*30*24, context=chat_id)
jobs[chat_id] = job
jq.put(job, next_t=0.0)
elif user_response == "once a week":
job = Job(turtle_callback, 60*60*24*7, context=chat_id)
jobs[chat_id] = job
jq.put(job, next_t=0.0)
elif user_response == "stop" or user_response == "never":
stop(bot, update)
updater = Updater(keys.bot_key)
jobs = {}
jq = updater.job_queue
dp = updater.dispatcher
# Cat A Day Handlers
dp.add_handler(CommandHandler('start', start))
dp.add_handler(CommandHandler('stop', stop))
dp.add_handler(CommandHandler('turtle', turtle))
# Message Handlers
dp.add_handler(MessageHandler(Filters.text, parse_message_response, pass_job_queue=True))
updater.start_polling()
updater.idle() | bot.py | import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, Job
import os
import keys
import random
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
def start(bot, update):
update.message.reply_text(
'Hi {}'.format(update.message.from_user.first_name))
schedule_keyboard = [['Once a day', 'Twice a day'],
['Once a week', 'Never']]
reply_markup = telegram.ReplyKeyboardMarkup(schedule_keyboard,
one_time_keyboard=True)
bot.send_message(chat_id=update.message.chat_id,
text="Choose a turtle delivery frequency",
reply_markup=reply_markup)
def stop(bot, update):
jobs[update.message.chat_id].schedule_removal()
bot.send_message(chat_id=update.message.chat_id,
text="Turtle delivered stopped")
def turtle(bot, update):
print "turtle"
send_turtle(bot, update.message.chat_id)
def send_turtle(bot, c_id):
bot.send_chat_action(chat_id=c_id,
action=telegram.ChatAction.TYPING)
turtle_photos = os.listdir('turtles')
rand_turtle = turtle_photos[random.randint(0, len(turtle_photos)-1)]
if '.gif' in rand_turtle:
print "gif"
bot.send_document(chat_id=c_id,
document=open('turtles/{}'.format(rand_turtle)))
else:
bot.send_photo(chat_id=c_id,
photo=open('turtles/{}'.format(rand_turtle)))
def turtle_callback(bot, job):
send_turtle(bot, job.context)
def parse_message_response(bot, update, job_queue):
print "test"
chat_id = update.message.chat_id
user_response = update.message.text.lower()
if user_response == "fast":
job = Job(turtle_callback, 10.0, context=chat_id)
jobs[chat_id] = job
jq.put(job, next_t=0.0)
elif user_response == "once a day":
job = Job(turtle_callback, 60*60*24, context=chat_id)
jobs[chat_id] = job
jq.put(job, next_t=0.0)
elif user_response == "twice a day":
job = Job(turtle_callback, 60*30*24, context=chat_id)
jobs[chat_id] = job
jq.put(job, next_t=0.0)
elif user_response == "once a week":
job = Job(turtle_callback, 60*60*24*7, context=chat_id)
jobs[chat_id] = job
jq.put(job, next_t=0.0)
elif user_response == "stop" or user_response == "never":
stop(bot, update)
updater = Updater(keys.bot_key)
jobs = {}
jq = updater.job_queue
dp = updater.dispatcher
# Cat A Day Handlers
dp.add_handler(CommandHandler('start', start))
dp.add_handler(CommandHandler('stop', stop))
dp.add_handler(CommandHandler('turtle', turtle))
# Message Handlers
dp.add_handler(MessageHandler(Filters.text, parse_message_response, pass_job_queue=True))
updater.start_polling()
updater.idle() | 0.208501 | 0.086093 |
import unittest
import servertest
import dxapi
class TestTickDB(servertest.TBServerTest):
streamKeys = [
'bars1min', 'tradeBBO', 'l2'
]
def test_isOpen(self):
self.assertTrue(self.db.isOpen())
def test_isReadOnly(self):
self.assertFalse(self.db.isReadOnly())
def test_createStream(self):
key = self.streamKeys[1]
try:
with open('testdata/' + key + '.xml', 'r') as schemaFile:
schema = schemaFile.read()
options = dxapi.StreamOptions()
options.name(key)
options.description(key)
options.scope = dxapi.StreamScope('DURABLE')
options.distributionFactor = 1
options.highAvailability = False
options.polymorphic = False
options.metadata(schema)
self.db.createStream(key, options)
stream = self.db.getStream(key)
self.assertIsNotNone(stream)
self.assertEqual(stream.key(), key)
self.assertEqual(stream.name(), key)
self.assertEqual(stream.distributionFactor(), 1)
self.assertEqual(stream.description(), key)
self.assertEqual(stream.highAvailability(), False)
self.assertEqual(stream.polymorphic(), False)
self.assertEqual(stream.periodicity(), 'IRREGULAR')
self.assertIsNone(stream.location())
self.assertIsNotNone(stream.metadata())
self.assertEqual(str(stream.scope()), 'DURABLE')
self.assertEqual(stream.unique(), False)
finally:
self.deleteStream(key)
def test_createStreamQQL(self):
key = self.streamKeys[1]
try:
self.createStreamQQL(key)
stream = self.db.getStream(key)
self.assertIsNotNone(stream)
self.assertEqual(stream.key(), key)
self.assertEqual(stream.name(), key)
self.assertEqual(stream.distributionFactor(), 0)
self.assertEqual(stream.description(), key)
self.assertEqual(stream.highAvailability(), False)
self.assertEqual(stream.polymorphic(), True)
self.assertEqual(stream.periodicity(), 'IRREGULAR')
self.assertIsNone(stream.location())
self.assertIsNotNone(stream.metadata())
self.assertEqual(str(stream.scope()), 'DURABLE')
self.assertEqual(stream.unique(), False)
finally:
self.deleteStream(key)
def test_listStreams(self):
try:
self.createStreams()
keySet = set(self.streamKeys)
keySet.add('events#')
streams = self.db.listStreams()
self.assertEqual(len(streams), len(keySet))
for stream in streams:
keySet.remove(stream.key())
self.assertEqual(len(keySet), 0)
finally:
self.deleteStreams()
def test_removeStream(self):
key = 'l2'
try:
self.createStream(key)
stream = self.db.getStream(key)
self.assertIsNotNone(stream)
stream.deleteStream()
stream = self.db.getStream(key)
self.assertIsNone(stream)
finally:
self.deleteStream(key)
# helpers
def createStreams(self):
for key in self.streamKeys:
self.createStream(key)
def deleteStreams(self):
for key in self.streamKeys:
self.deleteStream(key)
if __name__ == '__main__':
unittest.main() | python/test/TestTickDB.py | import unittest
import servertest
import dxapi
class TestTickDB(servertest.TBServerTest):
streamKeys = [
'bars1min', 'tradeBBO', 'l2'
]
def test_isOpen(self):
self.assertTrue(self.db.isOpen())
def test_isReadOnly(self):
self.assertFalse(self.db.isReadOnly())
def test_createStream(self):
key = self.streamKeys[1]
try:
with open('testdata/' + key + '.xml', 'r') as schemaFile:
schema = schemaFile.read()
options = dxapi.StreamOptions()
options.name(key)
options.description(key)
options.scope = dxapi.StreamScope('DURABLE')
options.distributionFactor = 1
options.highAvailability = False
options.polymorphic = False
options.metadata(schema)
self.db.createStream(key, options)
stream = self.db.getStream(key)
self.assertIsNotNone(stream)
self.assertEqual(stream.key(), key)
self.assertEqual(stream.name(), key)
self.assertEqual(stream.distributionFactor(), 1)
self.assertEqual(stream.description(), key)
self.assertEqual(stream.highAvailability(), False)
self.assertEqual(stream.polymorphic(), False)
self.assertEqual(stream.periodicity(), 'IRREGULAR')
self.assertIsNone(stream.location())
self.assertIsNotNone(stream.metadata())
self.assertEqual(str(stream.scope()), 'DURABLE')
self.assertEqual(stream.unique(), False)
finally:
self.deleteStream(key)
def test_createStreamQQL(self):
key = self.streamKeys[1]
try:
self.createStreamQQL(key)
stream = self.db.getStream(key)
self.assertIsNotNone(stream)
self.assertEqual(stream.key(), key)
self.assertEqual(stream.name(), key)
self.assertEqual(stream.distributionFactor(), 0)
self.assertEqual(stream.description(), key)
self.assertEqual(stream.highAvailability(), False)
self.assertEqual(stream.polymorphic(), True)
self.assertEqual(stream.periodicity(), 'IRREGULAR')
self.assertIsNone(stream.location())
self.assertIsNotNone(stream.metadata())
self.assertEqual(str(stream.scope()), 'DURABLE')
self.assertEqual(stream.unique(), False)
finally:
self.deleteStream(key)
def test_listStreams(self):
try:
self.createStreams()
keySet = set(self.streamKeys)
keySet.add('events#')
streams = self.db.listStreams()
self.assertEqual(len(streams), len(keySet))
for stream in streams:
keySet.remove(stream.key())
self.assertEqual(len(keySet), 0)
finally:
self.deleteStreams()
def test_removeStream(self):
key = 'l2'
try:
self.createStream(key)
stream = self.db.getStream(key)
self.assertIsNotNone(stream)
stream.deleteStream()
stream = self.db.getStream(key)
self.assertIsNone(stream)
finally:
self.deleteStream(key)
# helpers
def createStreams(self):
for key in self.streamKeys:
self.createStream(key)
def deleteStreams(self):
for key in self.streamKeys:
self.deleteStream(key)
if __name__ == '__main__':
unittest.main() | 0.436382 | 0.522933 |
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Customer',
fields=[
('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(max_length=254, unique=True, verbose_name='name')),
('description', models.TextField(blank=True, verbose_name='description')),
('status', models.CharField(choices=[('ACTIVE', 'Active'), ('ARCHIVED', 'Archived')], default='ACTIVE', max_length=100, verbose_name='status')),
],
options={
'verbose_name': 'Customer',
'verbose_name_plural': 'Customers',
},
),
migrations.CreateModel(
name='Project',
fields=[
('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(max_length=254, verbose_name='name')),
('description', models.TextField(blank=True, verbose_name='description')),
('status', models.CharField(choices=[('ACTIVE', 'Active'), ('ARCHIVED', 'Archived')], default='ACTIVE', max_length=100, verbose_name='status')),
('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='projects', to='tasks.customer', verbose_name='customer')),
],
options={
'verbose_name': 'Project',
'verbose_name_plural': 'Projects',
'unique_together': {('customer', 'name')},
},
),
migrations.CreateModel(
name='Task',
fields=[
('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(max_length=254, verbose_name='name')),
('description', models.TextField(blank=True, verbose_name='description')),
('status', models.CharField(choices=[('NEW', 'New'), ('PLANNING', 'Planning'), ('IN_PROGRESS', 'In Progress'), ('REVIEW', 'Review'), ('DONE', 'Done'), ('WONT_DO', "Won't do")], default='NEW', max_length=100, verbose_name='status')),
('estimate', models.DurationField(blank=True, null=True, verbose_name='estimate')),
('deadline', models.DateField(blank=True, null=True, verbose_name='deadline')),
('type_of_work', models.CharField(choices=[('BILLABLE', 'Billable'), ('NON_BILLABLE', 'Non Billable')], default='BILLABLE', max_length=100, verbose_name='type of work')),
('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tasks', to='tasks.project', verbose_name='project')),
],
options={
'verbose_name': 'Task',
'verbose_name_plural': 'Tasks',
'unique_together': {('project', 'name')},
},
),
] | opentimesheet/tasks/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Customer',
fields=[
('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(max_length=254, unique=True, verbose_name='name')),
('description', models.TextField(blank=True, verbose_name='description')),
('status', models.CharField(choices=[('ACTIVE', 'Active'), ('ARCHIVED', 'Archived')], default='ACTIVE', max_length=100, verbose_name='status')),
],
options={
'verbose_name': 'Customer',
'verbose_name_plural': 'Customers',
},
),
migrations.CreateModel(
name='Project',
fields=[
('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(max_length=254, verbose_name='name')),
('description', models.TextField(blank=True, verbose_name='description')),
('status', models.CharField(choices=[('ACTIVE', 'Active'), ('ARCHIVED', 'Archived')], default='ACTIVE', max_length=100, verbose_name='status')),
('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='projects', to='tasks.customer', verbose_name='customer')),
],
options={
'verbose_name': 'Project',
'verbose_name_plural': 'Projects',
'unique_together': {('customer', 'name')},
},
),
migrations.CreateModel(
name='Task',
fields=[
('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(max_length=254, verbose_name='name')),
('description', models.TextField(blank=True, verbose_name='description')),
('status', models.CharField(choices=[('NEW', 'New'), ('PLANNING', 'Planning'), ('IN_PROGRESS', 'In Progress'), ('REVIEW', 'Review'), ('DONE', 'Done'), ('WONT_DO', "Won't do")], default='NEW', max_length=100, verbose_name='status')),
('estimate', models.DurationField(blank=True, null=True, verbose_name='estimate')),
('deadline', models.DateField(blank=True, null=True, verbose_name='deadline')),
('type_of_work', models.CharField(choices=[('BILLABLE', 'Billable'), ('NON_BILLABLE', 'Non Billable')], default='BILLABLE', max_length=100, verbose_name='type of work')),
('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tasks', to='tasks.project', verbose_name='project')),
],
options={
'verbose_name': 'Task',
'verbose_name_plural': 'Tasks',
'unique_together': {('project', 'name')},
},
),
] | 0.511473 | 0.12424 |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# MIT License for more details.
"""This is a base class of the dataset."""
import importlib
from copy import deepcopy
from mmcv.runner import get_dist_info
from torch.utils import data as torch_data
from ..samplers import DistributedSampler
from vega.core.common.task_ops import TaskOps
from vega.datasets.pytorch.common.transforms import Transforms
from vega.core.common.class_factory import ClassFactory, ClassType
from vega.core.common.config import Config
from vega.core.common.utils import update_dict
class Dataset(TaskOps):
"""This is the base class of the dataset, which is a subclass of `TaskOps`.
The Dataset provide several basic attribute like dataloader, transform and sampler.
"""
__cls_dict__ = dict()
def __new__(cls, hps=None, **kwargs):
"""Construct method."""
if "dataset_type" in kwargs.keys():
t_cls = ClassFactory.get_cls(ClassType.DATASET, kwargs["dataset_type"])
else:
t_cls = ClassFactory.get_cls(ClassType.DATASET)
return super(Dataset, cls).__new__(t_cls)
def __init__(self, hps=None, **kwargs):
"""Construct method."""
default_config = {
'batch_size': 1,
'num_workers': 0,
'shuffle': False,
'distributed': False,
'imgs_per_gpu': 1,
'pin_memory': True,
'drop_last': True
}
self.mode = "train"
if "mode" in kwargs.keys():
self.mode = kwargs["mode"]
if hps is not None:
self._init_hps(hps)
if 'common' in self.cfg.keys() and self.cfg['common'] is not None:
common = deepcopy(self.cfg['common'])
self.args = update_dict(common, deepcopy(self.cfg[self.mode]))
else:
self.args = deepcopy(self.cfg[self.mode])
self.args = update_dict(self.args, Config(default_config))
for key in kwargs.keys():
if key in self.args:
self.args[key] = kwargs[key]
self.train = self.mode in ["train", "val"]
transforms_list = self._init_transforms()
self._transforms = Transforms(transforms_list)
if "transforms" in kwargs.keys():
self._transforms.__transform__ = kwargs["transforms"]
self.sampler = self._init_sampler()
def _init_hps(self, hps):
"""Convert trainer values in hps to cfg."""
if hps.get("dataset") is not None:
self.cfg.train = Config(update_dict(hps.dataset, self.cfg.train))
self.cfg = Config(update_dict(hps.trainer, self.cfg))
@classmethod
def register(cls, name):
"""Register user's dataset in Dataset.
:param name: class of user's registered dataset
:type name: class
"""
if name in cls.__cls_dict__:
raise ValueError("Cannot register name ({}) in Dataset".format(name))
cls.__cls_dict__[name.__name__] = name
@classmethod
def get_cls(cls, name):
"""Get concrete dataset class.
:param name: name of dataset
:type name: str
"""
if name not in cls.__cls_dict__:
raise ValueError("Cannot found name ({}) in Dataset".format((name)))
return cls.__cls_dict__[name]
@property
def dataloader(self):
"""Dataloader arrtribute which is a unified interface to generate the data.
:return: a batch data
:rtype: dict, list, optional
"""
data_loader = torch_data.DataLoader(self,
batch_size=self.args.batch_size,
shuffle=self.args.shuffle,
num_workers=self.args.num_workers,
pin_memory=self.args.pin_memory,
sampler=self.sampler,
drop_last=self.args.drop_last)
return data_loader
@property
def transforms(self):
"""Transform function which can replace transforms."""
return self._transforms
@transforms.setter
def transforms(self, value):
"""Set function of transforms."""
if isinstance(value, list):
self.transforms.__transform__ = value
def _init_transforms(self):
"""Initialize sampler method.
:return: a list of object
:rtype: list
"""
if "transforms" in self.args.keys():
transforms = list()
if not isinstance(self.args.transforms, list):
self.args.transforms = [self.args.transforms]
for i in range(len(self.args.transforms)):
transform_name = self.args.transforms[i].pop("type")
kwargs = self.args.transforms[i]
if ClassFactory.is_exists(ClassType.TRANSFORM, transform_name):
transforms.append(ClassFactory.get_cls(ClassType.TRANSFORM, transform_name)(**kwargs))
else:
transforms.append(getattr(importlib.import_module('torchvision.transforms'),
transform_name)(**kwargs))
return transforms
else:
return list()
@property
def sampler(self):
"""Sampler function which can replace sampler."""
return self._sampler
@sampler.setter
def sampler(self, value):
"""Set function of sampler."""
self._sampler = value
def _init_sampler(self):
"""Initialize sampler method.
:return: if the distributed is True, return a sampler object, else return None
:rtype: an object or None
"""
if self.args.distributed:
rank, world_size = get_dist_info()
sampler = DistributedSampler(self,
num_replicas=world_size,
rank=rank,
shuffle=self.args.shuffle)
else:
sampler = None
return sampler
def __len__(self):
"""Get the length of the dataset."""
raise NotImplementedError
def __getitem__(self, index):
"""Get an item of the dataset according to the index."""
raise NotImplementedError | vega/datasets/pytorch/common/dataset.py |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# MIT License for more details.
"""This is a base class of the dataset."""
import importlib
from copy import deepcopy
from mmcv.runner import get_dist_info
from torch.utils import data as torch_data
from ..samplers import DistributedSampler
from vega.core.common.task_ops import TaskOps
from vega.datasets.pytorch.common.transforms import Transforms
from vega.core.common.class_factory import ClassFactory, ClassType
from vega.core.common.config import Config
from vega.core.common.utils import update_dict
class Dataset(TaskOps):
"""This is the base class of the dataset, which is a subclass of `TaskOps`.
The Dataset provide several basic attribute like dataloader, transform and sampler.
"""
__cls_dict__ = dict()
def __new__(cls, hps=None, **kwargs):
"""Construct method."""
if "dataset_type" in kwargs.keys():
t_cls = ClassFactory.get_cls(ClassType.DATASET, kwargs["dataset_type"])
else:
t_cls = ClassFactory.get_cls(ClassType.DATASET)
return super(Dataset, cls).__new__(t_cls)
def __init__(self, hps=None, **kwargs):
"""Construct method."""
default_config = {
'batch_size': 1,
'num_workers': 0,
'shuffle': False,
'distributed': False,
'imgs_per_gpu': 1,
'pin_memory': True,
'drop_last': True
}
self.mode = "train"
if "mode" in kwargs.keys():
self.mode = kwargs["mode"]
if hps is not None:
self._init_hps(hps)
if 'common' in self.cfg.keys() and self.cfg['common'] is not None:
common = deepcopy(self.cfg['common'])
self.args = update_dict(common, deepcopy(self.cfg[self.mode]))
else:
self.args = deepcopy(self.cfg[self.mode])
self.args = update_dict(self.args, Config(default_config))
for key in kwargs.keys():
if key in self.args:
self.args[key] = kwargs[key]
self.train = self.mode in ["train", "val"]
transforms_list = self._init_transforms()
self._transforms = Transforms(transforms_list)
if "transforms" in kwargs.keys():
self._transforms.__transform__ = kwargs["transforms"]
self.sampler = self._init_sampler()
def _init_hps(self, hps):
"""Convert trainer values in hps to cfg."""
if hps.get("dataset") is not None:
self.cfg.train = Config(update_dict(hps.dataset, self.cfg.train))
self.cfg = Config(update_dict(hps.trainer, self.cfg))
@classmethod
def register(cls, name):
"""Register user's dataset in Dataset.
:param name: class of user's registered dataset
:type name: class
"""
if name in cls.__cls_dict__:
raise ValueError("Cannot register name ({}) in Dataset".format(name))
cls.__cls_dict__[name.__name__] = name
@classmethod
def get_cls(cls, name):
"""Get concrete dataset class.
:param name: name of dataset
:type name: str
"""
if name not in cls.__cls_dict__:
raise ValueError("Cannot found name ({}) in Dataset".format((name)))
return cls.__cls_dict__[name]
@property
def dataloader(self):
"""Dataloader arrtribute which is a unified interface to generate the data.
:return: a batch data
:rtype: dict, list, optional
"""
data_loader = torch_data.DataLoader(self,
batch_size=self.args.batch_size,
shuffle=self.args.shuffle,
num_workers=self.args.num_workers,
pin_memory=self.args.pin_memory,
sampler=self.sampler,
drop_last=self.args.drop_last)
return data_loader
@property
def transforms(self):
"""Transform function which can replace transforms."""
return self._transforms
@transforms.setter
def transforms(self, value):
"""Set function of transforms."""
if isinstance(value, list):
self.transforms.__transform__ = value
def _init_transforms(self):
"""Initialize sampler method.
:return: a list of object
:rtype: list
"""
if "transforms" in self.args.keys():
transforms = list()
if not isinstance(self.args.transforms, list):
self.args.transforms = [self.args.transforms]
for i in range(len(self.args.transforms)):
transform_name = self.args.transforms[i].pop("type")
kwargs = self.args.transforms[i]
if ClassFactory.is_exists(ClassType.TRANSFORM, transform_name):
transforms.append(ClassFactory.get_cls(ClassType.TRANSFORM, transform_name)(**kwargs))
else:
transforms.append(getattr(importlib.import_module('torchvision.transforms'),
transform_name)(**kwargs))
return transforms
else:
return list()
@property
def sampler(self):
"""Sampler function which can replace sampler."""
return self._sampler
@sampler.setter
def sampler(self, value):
"""Set function of sampler."""
self._sampler = value
def _init_sampler(self):
"""Initialize sampler method.
:return: if the distributed is True, return a sampler object, else return None
:rtype: an object or None
"""
if self.args.distributed:
rank, world_size = get_dist_info()
sampler = DistributedSampler(self,
num_replicas=world_size,
rank=rank,
shuffle=self.args.shuffle)
else:
sampler = None
return sampler
def __len__(self):
"""Get the length of the dataset."""
raise NotImplementedError
def __getitem__(self, index):
"""Get an item of the dataset according to the index."""
raise NotImplementedError | 0.900952 | 0.215402 |
from django.test import TestCase
import adapter
class AdapterTest(TestCase):
record = {
u'location': u'5109 W. STILES ST.\r\n5111-13 W. STILES ST.',
u'violation_code': u'CP-802',
u'violation_details_id': 2729519,
u'__metadata': {
u'type': u'PlanPhillyModel.violationdetails',
u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/violationdetails(2729519)'
},
u'locations': {
u'council_district': u'03',
u'zoningboardappeals': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)/zoningboardappeals'}},
u'street_name': u'51ST',
u'census_tract': u'111',
u'violationdetails': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)/violationdetails'}},
u'licenses': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)/licenses'}},
u'condo_unit': u'0000000',
u'location_id': 690752,
u'cases': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)/cases'}},
u'city': u'PHILADELPHIA',
u'zip': u'19131-4401',
u'street_suffix': u'ST',
u'appealhearings': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)/appealhearings'}},
u'state': u'PA',
u'unit_number': u'0000000',
u'census_block': None,
u'buildingboardappeals': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)/buildingboardappeals'}},
u'lireviewboardappeals': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)/lireviewboardappeals'}},
u'ward': u'44',
u'street_number': u' 01220',
u'permits': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)/permits'}},
u'__metadata': {
u'type': u'PlanPhillyModel.locations',
u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)'
},
u'y': u'242944',
u'x': u'2676373',
u'street_direction': u'N'
},
u'violation_code_description': u'DUMPING - PRIVATE LOT',
u'violation_datetime': u'/Date(1362114000000)/',
u'case_number': u'371285',
u'cases': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/violationdetails(2729519)/cases'}},
u'location_id': 690752,
u'violation_status': u'Complied'
}
def test_get_location(self):
location = adapter.get_location(self.record)
self.assertIsNotNone(location.point)
def test_get_violation_type(self):
violation_type = adapter.get_violation_type(self.record)
self.assertEqual(violation_type.code, self.record['violation_code']) | phillydata/violations/tests.py | from django.test import TestCase
import adapter
class AdapterTest(TestCase):
record = {
u'location': u'5109 W. STILES ST.\r\n5111-13 W. STILES ST.',
u'violation_code': u'CP-802',
u'violation_details_id': 2729519,
u'__metadata': {
u'type': u'PlanPhillyModel.violationdetails',
u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/violationdetails(2729519)'
},
u'locations': {
u'council_district': u'03',
u'zoningboardappeals': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)/zoningboardappeals'}},
u'street_name': u'51ST',
u'census_tract': u'111',
u'violationdetails': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)/violationdetails'}},
u'licenses': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)/licenses'}},
u'condo_unit': u'0000000',
u'location_id': 690752,
u'cases': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)/cases'}},
u'city': u'PHILADELPHIA',
u'zip': u'19131-4401',
u'street_suffix': u'ST',
u'appealhearings': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)/appealhearings'}},
u'state': u'PA',
u'unit_number': u'0000000',
u'census_block': None,
u'buildingboardappeals': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)/buildingboardappeals'}},
u'lireviewboardappeals': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)/lireviewboardappeals'}},
u'ward': u'44',
u'street_number': u' 01220',
u'permits': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)/permits'}},
u'__metadata': {
u'type': u'PlanPhillyModel.locations',
u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/locations(690752)'
},
u'y': u'242944',
u'x': u'2676373',
u'street_direction': u'N'
},
u'violation_code_description': u'DUMPING - PRIVATE LOT',
u'violation_datetime': u'/Date(1362114000000)/',
u'case_number': u'371285',
u'cases': {u'__deferred': {u'uri': u'http://services.phila.gov/PhillyAPI/Data/v0.7/Service.svc/violationdetails(2729519)/cases'}},
u'location_id': 690752,
u'violation_status': u'Complied'
}
def test_get_location(self):
location = adapter.get_location(self.record)
self.assertIsNotNone(location.point)
def test_get_violation_type(self):
violation_type = adapter.get_violation_type(self.record)
self.assertEqual(violation_type.code, self.record['violation_code']) | 0.416203 | 0.134009 |
from typing import List, Tuple
__author__ = 'Laptop$'
__date__ = '2017-07-16'
__description__ = " "
__version__ = '1.0'
import datetime
import re
import matplotlib.pyplot as plt
import pandas as pd
from hydsensread.file_reader.abstract_file_reader import TimeSeriesFileReader, date_list, LineDefinition
class XLSHannaFileReader(TimeSeriesFileReader):
def __init__(self, file_path: str = None, header_length: int = 10,wait_read:bool = False):
super().__init__(file_path, header_length,wait_read=wait_read)
def read_file(self):
self._date_list = self._get_date_list()
super(XLSHannaFileReader, self).read_file()
@property
def header_info(self):
return self.file_content[' Lot Info ']
@property
def data_sheet(self):
return self.file_content[' Log data - 1']
def _read_file_header(self):
"""
implementation of the base class abstract method
"""
for row in self.header_info:
if row[0] is None or row[0] in ['GENERAL INFORMATION', 'LOT INFORMATION', 'SETTINGS']:
pass
else:
key = re.sub('^ *', '', row[0])
self.header_content[key] = row[1]
def _get_date_list(self) -> date_list:
date_list = [d[0] for d in self.data_sheet[1:]]
time_list = [datetime.time(d[1].hour, d[1].minute, d[1].second) for d in self.data_sheet[1:]]
date_time = [datetime.datetime(d.year, d.month, d.day, t.hour, t.minute, t.second)
for d, t in zip(date_list, time_list)]
return date_time
def _read_file_data(self):
"""
implementation of the base class abstract method
"""
values = [val[2:] for val in self.data_sheet[1:]]
self._site_of_interest.records = pd.DataFrame(data=values, columns=self.data_sheet[0][2:],
index=self._date_list)
def _read_file_data_header(self):
"""
implementation of the base class abstract method
"""
self.sites.site_name = self.header_content['Lot Name']
self.sites.instrument_serial_number = self.header_content['Instrument Serial No.']
self.sites.visit_date = self.header_content['Started Date and Time']
def plot(self, *args, **kwargs) -> Tuple[
plt.Figure, List[plt.Axes]]:
main_temperature_line_def = LineDefinition('Temp.[°C]')
ph_line_def = LineDefinition('pH ', 'black', '--')
outward = 50
do_line_Def = LineDefinition('D.O.[%]', 'red', outward=outward)
orp_line_def = LineDefinition('ORP[mV]', 'green', outward=2 * outward)
other_axis = [ph_line_def, do_line_Def, orp_line_def]
fig, axes = super().plot(main_temperature_line_def, other_axis, *args, **kwargs)
return fig, axes
if __name__ == '__main__':
import os
import pprint
path = os.getcwd()
while os.path.split(path)[1] != "hydsensread":
path = os.path.split(path)[0]
file_loc = os.path.join(path, 'file_example')
file_name = 'LOG006_0621113447.xls'
file_name_2 = 'LOG001_1011105528.xls'
file = os.path.join(file_loc, file_name)
file_2 = os.path.join(file_loc, file_name_2)
print(file)
hanna_file = XLSHannaFileReader(file)
hanna_file.read_file()
pprint.pprint(hanna_file.header_content, width=250)
hanna_file_2 = XLSHannaFileReader(file_2)
hanna_file_2.read_file()
hanna_file_2.plot()
print(hanna_file.records.head())
print("*" * 15)
print(hanna_file_2.records.head())
hanna_file.plot(subplots=True, title=hanna_file.sites.site_name, x_compat=True)
plt.show(block=True) | hydsensread/file_reader/compagny_file_reader/hanna_file_reader.py | from typing import List, Tuple
__author__ = 'Laptop$'
__date__ = '2017-07-16'
__description__ = " "
__version__ = '1.0'
import datetime
import re
import matplotlib.pyplot as plt
import pandas as pd
from hydsensread.file_reader.abstract_file_reader import TimeSeriesFileReader, date_list, LineDefinition
class XLSHannaFileReader(TimeSeriesFileReader):
def __init__(self, file_path: str = None, header_length: int = 10,wait_read:bool = False):
super().__init__(file_path, header_length,wait_read=wait_read)
def read_file(self):
self._date_list = self._get_date_list()
super(XLSHannaFileReader, self).read_file()
@property
def header_info(self):
return self.file_content[' Lot Info ']
@property
def data_sheet(self):
return self.file_content[' Log data - 1']
def _read_file_header(self):
"""
implementation of the base class abstract method
"""
for row in self.header_info:
if row[0] is None or row[0] in ['GENERAL INFORMATION', 'LOT INFORMATION', 'SETTINGS']:
pass
else:
key = re.sub('^ *', '', row[0])
self.header_content[key] = row[1]
def _get_date_list(self) -> date_list:
date_list = [d[0] for d in self.data_sheet[1:]]
time_list = [datetime.time(d[1].hour, d[1].minute, d[1].second) for d in self.data_sheet[1:]]
date_time = [datetime.datetime(d.year, d.month, d.day, t.hour, t.minute, t.second)
for d, t in zip(date_list, time_list)]
return date_time
def _read_file_data(self):
"""
implementation of the base class abstract method
"""
values = [val[2:] for val in self.data_sheet[1:]]
self._site_of_interest.records = pd.DataFrame(data=values, columns=self.data_sheet[0][2:],
index=self._date_list)
def _read_file_data_header(self):
"""
implementation of the base class abstract method
"""
self.sites.site_name = self.header_content['Lot Name']
self.sites.instrument_serial_number = self.header_content['Instrument Serial No.']
self.sites.visit_date = self.header_content['Started Date and Time']
def plot(self, *args, **kwargs) -> Tuple[
plt.Figure, List[plt.Axes]]:
main_temperature_line_def = LineDefinition('Temp.[°C]')
ph_line_def = LineDefinition('pH ', 'black', '--')
outward = 50
do_line_Def = LineDefinition('D.O.[%]', 'red', outward=outward)
orp_line_def = LineDefinition('ORP[mV]', 'green', outward=2 * outward)
other_axis = [ph_line_def, do_line_Def, orp_line_def]
fig, axes = super().plot(main_temperature_line_def, other_axis, *args, **kwargs)
return fig, axes
if __name__ == '__main__':
import os
import pprint
path = os.getcwd()
while os.path.split(path)[1] != "hydsensread":
path = os.path.split(path)[0]
file_loc = os.path.join(path, 'file_example')
file_name = 'LOG006_0621113447.xls'
file_name_2 = 'LOG001_1011105528.xls'
file = os.path.join(file_loc, file_name)
file_2 = os.path.join(file_loc, file_name_2)
print(file)
hanna_file = XLSHannaFileReader(file)
hanna_file.read_file()
pprint.pprint(hanna_file.header_content, width=250)
hanna_file_2 = XLSHannaFileReader(file_2)
hanna_file_2.read_file()
hanna_file_2.plot()
print(hanna_file.records.head())
print("*" * 15)
print(hanna_file_2.records.head())
hanna_file.plot(subplots=True, title=hanna_file.sites.site_name, x_compat=True)
plt.show(block=True) | 0.812198 | 0.225502 |
from typing import List
from fastapi import APIRouter, Depends, HTTPException, Response
from pydantic import conint
from redis import Redis
from scoretracker import players
from . import schemas
from .deps import get_redis
router = APIRouter(tags=["Games"])
@router.post(
"/games/new",
summary="Record a new game",
response_description="New Game",
response_model=schemas.GameResult,
status_code=201,
)
def new_game(data: schemas.GameCreate, redis: Redis = Depends(get_redis)):
game = schemas.Game(id=redis.incr("next_game_id"), **data.dict())
prefix = f"game:{game.id}"
if not redis.exists(f"user:{game.user_id}"):
raise HTTPException(404, detail="User does not exist.")
redis.set(prefix + ":user-id", game.user_id)
redis.set(prefix + ":name", game.name)
redis.set(prefix + ":other_team", game.other_team)
redis.set(prefix + ":date", str(game.date))
for player_id in game.player_ids:
if not redis.sismember("players", player_id):
raise HTTPException(404, detail="Player does not exist.")
redis.sadd(f"{prefix}:player-ids", player_id)
redis.sadd("games", game.id)
return game.convert(redis)
@router.get(
"/games/{game_id}", summary="Get game by id", response_model=schemas.GameResult
)
def get_game(game_id: conint(gt=0), redis: Redis = Depends(get_redis)):
if not redis.sismember("games", game_id):
raise HTTPException(404)
return schemas.GameResult.find(redis, game_id)
@router.get("/games", summary="Get all games", response_model=List[schemas.GameResult])
def all_games(redis: Redis = Depends(get_redis)):
return [
schemas.GameResult.find(redis, game_id) for game_id in redis.smembers("games")
]
@router.patch(
"/games/{game_id}",
summary="Edit a game",
response_model=schemas.GameResult,
responses={
200: {"description": "Game is edited"},
404: {"description": "Data does not exist to edit game"},
},
)
def edit_game(
data: schemas.GameCreate, game_id: conint(gt=0), redis: Redis = Depends(get_redis)
):
if not redis.sismember("games", game_id):
raise HTTPException(404)
game = schemas.Game(id=game_id, **data.dict())
prefix = f"game:{game.id}"
if not redis.exists(f"user:{game.user_id}"):
raise HTTPException(404, detail="User does not exist.")
redis.set(prefix + ":user-id", game.user_id)
redis.set(prefix + ":name", game.name)
redis.set(prefix + ":other_team", game.other_team)
redis.set(prefix + ":date", str(game.date))
for player_id in game.player_ids:
if not redis.sismember("players", player_id):
raise HTTPException(404)
redis.sadd(f"{prefix}:player-ids", player_id)
redis.sadd("games", game.id)
return game.convert(redis)
@router.delete(
"/games/{game_id}",
summary="Delete game by Id",
status_code=204,
responses={
404: {"description": "Game does not exist"},
204: {"description": "Game was successfully deleted"},
},
)
def delete_game(game_id: conint(gt=0), redis: Redis = Depends(get_redis)):
prefix = f"game:{game_id}"
if not redis.sismember("games", game_id):
raise HTTPException(404)
else:
redis.srem("games", game_id)
redis.delete(prefix + ":name")
redis.delete(prefix + ":other_team")
redis.delete(prefix + ":date")
redis.delete(prefix + "user_id")
redis.delete(prefix + "player-ids")
return Response(status_code=204) | scoretracker/games.py | from typing import List
from fastapi import APIRouter, Depends, HTTPException, Response
from pydantic import conint
from redis import Redis
from scoretracker import players
from . import schemas
from .deps import get_redis
router = APIRouter(tags=["Games"])
@router.post(
"/games/new",
summary="Record a new game",
response_description="New Game",
response_model=schemas.GameResult,
status_code=201,
)
def new_game(data: schemas.GameCreate, redis: Redis = Depends(get_redis)):
game = schemas.Game(id=redis.incr("next_game_id"), **data.dict())
prefix = f"game:{game.id}"
if not redis.exists(f"user:{game.user_id}"):
raise HTTPException(404, detail="User does not exist.")
redis.set(prefix + ":user-id", game.user_id)
redis.set(prefix + ":name", game.name)
redis.set(prefix + ":other_team", game.other_team)
redis.set(prefix + ":date", str(game.date))
for player_id in game.player_ids:
if not redis.sismember("players", player_id):
raise HTTPException(404, detail="Player does not exist.")
redis.sadd(f"{prefix}:player-ids", player_id)
redis.sadd("games", game.id)
return game.convert(redis)
@router.get(
"/games/{game_id}", summary="Get game by id", response_model=schemas.GameResult
)
def get_game(game_id: conint(gt=0), redis: Redis = Depends(get_redis)):
if not redis.sismember("games", game_id):
raise HTTPException(404)
return schemas.GameResult.find(redis, game_id)
@router.get("/games", summary="Get all games", response_model=List[schemas.GameResult])
def all_games(redis: Redis = Depends(get_redis)):
return [
schemas.GameResult.find(redis, game_id) for game_id in redis.smembers("games")
]
@router.patch(
"/games/{game_id}",
summary="Edit a game",
response_model=schemas.GameResult,
responses={
200: {"description": "Game is edited"},
404: {"description": "Data does not exist to edit game"},
},
)
def edit_game(
data: schemas.GameCreate, game_id: conint(gt=0), redis: Redis = Depends(get_redis)
):
if not redis.sismember("games", game_id):
raise HTTPException(404)
game = schemas.Game(id=game_id, **data.dict())
prefix = f"game:{game.id}"
if not redis.exists(f"user:{game.user_id}"):
raise HTTPException(404, detail="User does not exist.")
redis.set(prefix + ":user-id", game.user_id)
redis.set(prefix + ":name", game.name)
redis.set(prefix + ":other_team", game.other_team)
redis.set(prefix + ":date", str(game.date))
for player_id in game.player_ids:
if not redis.sismember("players", player_id):
raise HTTPException(404)
redis.sadd(f"{prefix}:player-ids", player_id)
redis.sadd("games", game.id)
return game.convert(redis)
@router.delete(
"/games/{game_id}",
summary="Delete game by Id",
status_code=204,
responses={
404: {"description": "Game does not exist"},
204: {"description": "Game was successfully deleted"},
},
)
def delete_game(game_id: conint(gt=0), redis: Redis = Depends(get_redis)):
prefix = f"game:{game_id}"
if not redis.sismember("games", game_id):
raise HTTPException(404)
else:
redis.srem("games", game_id)
redis.delete(prefix + ":name")
redis.delete(prefix + ":other_team")
redis.delete(prefix + ":date")
redis.delete(prefix + "user_id")
redis.delete(prefix + "player-ids")
return Response(status_code=204) | 0.638723 | 0.165965 |
import os
import subprocess
import traceback
from pkg_resources import resource_filename
from typing import List
import pretty_midi
from sinethesizer.io import (
convert_events_to_timeline,
convert_tsv_to_events,
create_instruments_registry,
write_timeline_to_wav
)
from sinethesizer.utils.music_theory import get_list_of_notes
N_EIGHTHS_PER_MEASURE = 8
def create_midi_from_piece(
piece: 'rlmusician.environment.Piece',
midi_path: str,
measure_in_seconds: float,
cantus_firmus_instrument: int,
counterpoint_instrument: int,
velocity: int,
trailing_silence_in_measures: int = 2
) -> None:
"""
Create MIDI file from a piece created by this package.
:param piece:
`Piece` instance
:param midi_path:
path where resulting MIDI file is going to be saved
:param measure_in_seconds:
duration of one measure in seconds
:param cantus_firmus_instrument:
for an instrument that plays cantus firmus, its ID (number)
according to General MIDI specification
:param counterpoint_instrument:
for an instrument that plays counterpoint line, its ID (number)
according to General MIDI specification
:param velocity:
one common velocity for all notes
:param trailing_silence_in_measures:
number of measures with silence to add at the end of the composition
:return:
None
"""
numeration_shift = pretty_midi.note_name_to_number('A0')
lines = [
piece.cantus_firmus,
piece.counterpoint
]
pretty_midi_instruments = [
pretty_midi.Instrument(program=cantus_firmus_instrument),
pretty_midi.Instrument(program=counterpoint_instrument)
]
for line, pretty_midi_instrument in zip(lines, pretty_midi_instruments):
for element in line:
pitch = (
element.scale_element.position_in_semitones
+ numeration_shift
)
start_time = (
element.start_time_in_eighths
/ N_EIGHTHS_PER_MEASURE
* measure_in_seconds
)
end_time = (
element.end_time_in_eighths
/ N_EIGHTHS_PER_MEASURE
* measure_in_seconds
)
note = pretty_midi.Note(
velocity=velocity,
pitch=pitch,
start=start_time,
end=end_time
)
pretty_midi_instrument.notes.append(note)
pretty_midi_instrument.notes.sort(key=lambda x: x.start)
start_time = piece.n_measures * measure_in_seconds
end_time = start_time + trailing_silence_in_measures * measure_in_seconds
note = pretty_midi.Note(
velocity=0,
pitch=1, # Arbitrary value that affects nothing.
start=start_time,
end=end_time
)
pretty_midi_instruments[0].notes.append(note)
composition = pretty_midi.PrettyMIDI()
for pretty_midi_instrument in pretty_midi_instruments:
composition.instruments.append(pretty_midi_instrument)
composition.write(midi_path)
def create_events_from_piece(
piece: 'rlmusician.environment.Piece',
events_path: str,
measure_in_seconds: float,
cantus_firmus_instrument: str,
counterpoint_instrument: str,
velocity: float,
effects: str = ''
) -> None:
"""
Create TSV file with `sinethesizer` events from a piece.
:param piece:
`Piece` instance
:param events_path:
path to a file where result is going to be saved
:param measure_in_seconds:
duration of one measure in seconds
:param cantus_firmus_instrument:
instrument to be used to play cantus firmus
:param counterpoint_instrument:
instrument to be used to play counterpoint line
:param velocity:
one common velocity for all notes
:param effects:
sound effects to be applied to the resulting event
:return:
None
"""
all_notes = get_list_of_notes()
eight_in_seconds = measure_in_seconds / N_EIGHTHS_PER_MEASURE
events = []
lines = [piece.cantus_firmus, piece.counterpoint]
line_ids = ['cantus_firmus', 'counterpoint']
instruments = [cantus_firmus_instrument, counterpoint_instrument]
for line, line_id, instrument in zip(lines, line_ids, instruments):
for element in line:
start_time = element.start_time_in_eighths * eight_in_seconds
duration = (
(element.end_time_in_eighths - element.start_time_in_eighths)
* eight_in_seconds
)
pitch_id = element.scale_element.position_in_semitones
note = all_notes[pitch_id]
event = (instrument, start_time, duration, note, pitch_id, line_id)
events.append(event)
events = sorted(events, key=lambda x: (x[1], x[4], x[2]))
events = [
f"{x[0]}\t{x[1]}\t{x[2]}\t{x[3]}\t{velocity}\t{effects}\t{x[5]}"
for x in events
]
columns = [
'instrument', 'start_time', 'duration', 'frequency',
'velocity', 'effects', 'line_id'
]
header = '\t'.join(columns)
results = [header] + events
with open(events_path, 'w') as out_file:
for line in results:
out_file.write(line + '\n')
def create_wav_from_events(events_path: str, output_path: str) -> None:
"""
Create WAV file based on `sinethesizer` TSV file.
:param events_path:
path to TSV file with track represented as `sinethesizer` events
:param output_path:
path where resulting WAV file is going to be saved
:return:
None
"""
presets_path = resource_filename(
'rlmusician',
'configs/sinethesizer_presets.yml'
)
settings = {
'frame_rate': 48000,
'trailing_silence': 2,
'peak_amplitude': 1,
'instruments_registry': create_instruments_registry(presets_path)
}
events = convert_tsv_to_events(events_path, settings)
timeline = convert_events_to_timeline(events, settings)
write_timeline_to_wav(output_path, timeline, settings['frame_rate'])
def make_lilypond_template(tonic: str, scale_type: str) -> str:
"""
Make template of Lilypond text file.
:param tonic:
tonic pitch class represented by letter (like C or A#)
:param scale_type:
type of scale (e.g., 'major', 'natural_minor', or 'harmonic_minor')
:return:
template
"""
raw_template = (
"\\version \"2.18.2\"\n"
"\\layout {{{{\n"
" indent = #0\n"
"}}}}\n"
"\\new StaffGroup <<\n"
" \\new Staff <<\n"
" \\clef treble\n"
" \\time 4/4\n"
" \\key {} \\{}\n"
" {{{{{{}}}}}}\n"
" \\\\\n"
" {{{{{{}}}}}}\n"
" >>\n"
">>"
)
tonic = tonic.replace('#', 'is').replace('b', 'es').lower()
scale_type = scale_type.split('_')[-1]
template = raw_template.format(tonic, scale_type)
return template
def convert_to_lilypond_note(
line_element: 'rlmusician.environment.piece.LineElement'
) -> str:
"""
Convert `LineElement` instance to note in Lilypond absolute notation.
:param line_element:
element of a melodic line
:return:
note in Lilypond absolute notation
"""
pitch_class = line_element.scale_element.note[:-1]
pitch_class = pitch_class.replace('#', 'is').replace('b', 'es')
pitch_class = pitch_class.lower()
octave_id = int(line_element.scale_element.note[-1])
lilypond_default_octave_id = 3
octave_diff = octave_id - lilypond_default_octave_id
octave_sign = "'" if octave_diff >= 0 else ','
octave_info = "".join(octave_sign for _ in range(abs(octave_diff)))
start_time = line_element.start_time_in_eighths
end_time = line_element.end_time_in_eighths
time_from_measure_start = start_time % N_EIGHTHS_PER_MEASURE
duration_in_measures = (end_time - start_time) / N_EIGHTHS_PER_MEASURE
if duration_in_measures == 1.0 and time_from_measure_start > 0:
filled_measure_share = time_from_measure_start / N_EIGHTHS_PER_MEASURE
remaining_duration = int(round(1 / (1 - filled_measure_share)))
remaining_note = f"{pitch_class}{octave_info}{remaining_duration}~"
left_over_bar_duration = int(round(1 / filled_measure_share))
left_over_note = f"{pitch_class}{octave_info}{left_over_bar_duration}"
return f"{remaining_note} {left_over_note}"
else:
duration = int(round((1 / duration_in_measures)))
note = f"{pitch_class}{octave_info}{duration}"
return note
def combine_lilypond_voices(
counterpoint_voice: str,
cantus_firmus_voice: str,
is_counterpoint_above: bool,
counterpoint_start_pause_in_eighths: int
) -> List[str]:
"""
Sort Lilypond voices and add delay to counterpoint voice if needed.
:param counterpoint_voice:
Lilypond representation of counterpoint line (without pauses)
:param cantus_firmus_voice:
Lilypond representation of cantus firmus line
:param is_counterpoint_above:
indicator whether counterpoint is written above cantus firmus
:param counterpoint_start_pause_in_eighths:
duration of pause that opens counterpoint line (in eighths of measure)
:return:
combined Lilypond representations
"""
if counterpoint_start_pause_in_eighths > 0:
pause_duration = int(round(
N_EIGHTHS_PER_MEASURE / counterpoint_start_pause_in_eighths
))
pause = f'r{pause_duration}'
counterpoint_voice = pause + ' ' + counterpoint_voice
if is_counterpoint_above:
return [counterpoint_voice, cantus_firmus_voice]
else:
return [cantus_firmus_voice, counterpoint_voice]
def create_lilypond_file_from_piece(
piece: 'rlmusician.environment.Piece',
output_path: str
) -> None:
"""
Create text file in format of Lilypond sheet music editor.
:param piece:
musical piece
:param output_path:
path where resulting file is going to be saved
:return:
None
"""
template = make_lilypond_template(piece.tonic, piece.scale_type)
lilypond_voices = {}
melodic_lines = {
'counterpoint': piece.counterpoint,
'cantus_firmus': piece.cantus_firmus
}
for line_id, melodic_line in melodic_lines.items():
lilypond_voice = []
for line_element in melodic_line:
note = convert_to_lilypond_note(line_element)
lilypond_voice.append(note)
lilypond_voice = " ".join(lilypond_voice)
lilypond_voices[line_id] = lilypond_voice
lilypond_voices = combine_lilypond_voices(
lilypond_voices['counterpoint'],
lilypond_voices['cantus_firmus'],
piece.is_counterpoint_above,
piece.counterpoint_specifications['start_pause_in_eighths']
)
result = template.format(*lilypond_voices)
with open(output_path, 'w') as out_file:
out_file.write(result)
def create_pdf_sheet_music_with_lilypond(
lilypond_path: str
) -> None: # pragma: no cover
"""
Create PDF file with sheet music.
:param lilypond_path:
path to a text file in Lilypond format
:return:
None:
"""
dir_path, filename = os.path.split(lilypond_path)
bash_command = f"lilypond {filename}"
try:
process = subprocess.Popen(
bash_command.split(),
cwd=dir_path,
stdout=subprocess.PIPE
)
process.communicate()
except Exception:
print("Rendering sheet music to PDF failed. Do you have Lilypond?")
print(traceback.format_exc()) | rlmusician/utils/io.py | import os
import subprocess
import traceback
from pkg_resources import resource_filename
from typing import List
import pretty_midi
from sinethesizer.io import (
convert_events_to_timeline,
convert_tsv_to_events,
create_instruments_registry,
write_timeline_to_wav
)
from sinethesizer.utils.music_theory import get_list_of_notes
N_EIGHTHS_PER_MEASURE = 8
def create_midi_from_piece(
piece: 'rlmusician.environment.Piece',
midi_path: str,
measure_in_seconds: float,
cantus_firmus_instrument: int,
counterpoint_instrument: int,
velocity: int,
trailing_silence_in_measures: int = 2
) -> None:
"""
Create MIDI file from a piece created by this package.
:param piece:
`Piece` instance
:param midi_path:
path where resulting MIDI file is going to be saved
:param measure_in_seconds:
duration of one measure in seconds
:param cantus_firmus_instrument:
for an instrument that plays cantus firmus, its ID (number)
according to General MIDI specification
:param counterpoint_instrument:
for an instrument that plays counterpoint line, its ID (number)
according to General MIDI specification
:param velocity:
one common velocity for all notes
:param trailing_silence_in_measures:
number of measures with silence to add at the end of the composition
:return:
None
"""
numeration_shift = pretty_midi.note_name_to_number('A0')
lines = [
piece.cantus_firmus,
piece.counterpoint
]
pretty_midi_instruments = [
pretty_midi.Instrument(program=cantus_firmus_instrument),
pretty_midi.Instrument(program=counterpoint_instrument)
]
for line, pretty_midi_instrument in zip(lines, pretty_midi_instruments):
for element in line:
pitch = (
element.scale_element.position_in_semitones
+ numeration_shift
)
start_time = (
element.start_time_in_eighths
/ N_EIGHTHS_PER_MEASURE
* measure_in_seconds
)
end_time = (
element.end_time_in_eighths
/ N_EIGHTHS_PER_MEASURE
* measure_in_seconds
)
note = pretty_midi.Note(
velocity=velocity,
pitch=pitch,
start=start_time,
end=end_time
)
pretty_midi_instrument.notes.append(note)
pretty_midi_instrument.notes.sort(key=lambda x: x.start)
start_time = piece.n_measures * measure_in_seconds
end_time = start_time + trailing_silence_in_measures * measure_in_seconds
note = pretty_midi.Note(
velocity=0,
pitch=1, # Arbitrary value that affects nothing.
start=start_time,
end=end_time
)
pretty_midi_instruments[0].notes.append(note)
composition = pretty_midi.PrettyMIDI()
for pretty_midi_instrument in pretty_midi_instruments:
composition.instruments.append(pretty_midi_instrument)
composition.write(midi_path)
def create_events_from_piece(
piece: 'rlmusician.environment.Piece',
events_path: str,
measure_in_seconds: float,
cantus_firmus_instrument: str,
counterpoint_instrument: str,
velocity: float,
effects: str = ''
) -> None:
"""
Create TSV file with `sinethesizer` events from a piece.
:param piece:
`Piece` instance
:param events_path:
path to a file where result is going to be saved
:param measure_in_seconds:
duration of one measure in seconds
:param cantus_firmus_instrument:
instrument to be used to play cantus firmus
:param counterpoint_instrument:
instrument to be used to play counterpoint line
:param velocity:
one common velocity for all notes
:param effects:
sound effects to be applied to the resulting event
:return:
None
"""
all_notes = get_list_of_notes()
eight_in_seconds = measure_in_seconds / N_EIGHTHS_PER_MEASURE
events = []
lines = [piece.cantus_firmus, piece.counterpoint]
line_ids = ['cantus_firmus', 'counterpoint']
instruments = [cantus_firmus_instrument, counterpoint_instrument]
for line, line_id, instrument in zip(lines, line_ids, instruments):
for element in line:
start_time = element.start_time_in_eighths * eight_in_seconds
duration = (
(element.end_time_in_eighths - element.start_time_in_eighths)
* eight_in_seconds
)
pitch_id = element.scale_element.position_in_semitones
note = all_notes[pitch_id]
event = (instrument, start_time, duration, note, pitch_id, line_id)
events.append(event)
events = sorted(events, key=lambda x: (x[1], x[4], x[2]))
events = [
f"{x[0]}\t{x[1]}\t{x[2]}\t{x[3]}\t{velocity}\t{effects}\t{x[5]}"
for x in events
]
columns = [
'instrument', 'start_time', 'duration', 'frequency',
'velocity', 'effects', 'line_id'
]
header = '\t'.join(columns)
results = [header] + events
with open(events_path, 'w') as out_file:
for line in results:
out_file.write(line + '\n')
def create_wav_from_events(events_path: str, output_path: str) -> None:
"""
Create WAV file based on `sinethesizer` TSV file.
:param events_path:
path to TSV file with track represented as `sinethesizer` events
:param output_path:
path where resulting WAV file is going to be saved
:return:
None
"""
presets_path = resource_filename(
'rlmusician',
'configs/sinethesizer_presets.yml'
)
settings = {
'frame_rate': 48000,
'trailing_silence': 2,
'peak_amplitude': 1,
'instruments_registry': create_instruments_registry(presets_path)
}
events = convert_tsv_to_events(events_path, settings)
timeline = convert_events_to_timeline(events, settings)
write_timeline_to_wav(output_path, timeline, settings['frame_rate'])
def make_lilypond_template(tonic: str, scale_type: str) -> str:
"""
Make template of Lilypond text file.
:param tonic:
tonic pitch class represented by letter (like C or A#)
:param scale_type:
type of scale (e.g., 'major', 'natural_minor', or 'harmonic_minor')
:return:
template
"""
raw_template = (
"\\version \"2.18.2\"\n"
"\\layout {{{{\n"
" indent = #0\n"
"}}}}\n"
"\\new StaffGroup <<\n"
" \\new Staff <<\n"
" \\clef treble\n"
" \\time 4/4\n"
" \\key {} \\{}\n"
" {{{{{{}}}}}}\n"
" \\\\\n"
" {{{{{{}}}}}}\n"
" >>\n"
">>"
)
tonic = tonic.replace('#', 'is').replace('b', 'es').lower()
scale_type = scale_type.split('_')[-1]
template = raw_template.format(tonic, scale_type)
return template
def convert_to_lilypond_note(
line_element: 'rlmusician.environment.piece.LineElement'
) -> str:
"""
Convert `LineElement` instance to note in Lilypond absolute notation.
:param line_element:
element of a melodic line
:return:
note in Lilypond absolute notation
"""
pitch_class = line_element.scale_element.note[:-1]
pitch_class = pitch_class.replace('#', 'is').replace('b', 'es')
pitch_class = pitch_class.lower()
octave_id = int(line_element.scale_element.note[-1])
lilypond_default_octave_id = 3
octave_diff = octave_id - lilypond_default_octave_id
octave_sign = "'" if octave_diff >= 0 else ','
octave_info = "".join(octave_sign for _ in range(abs(octave_diff)))
start_time = line_element.start_time_in_eighths
end_time = line_element.end_time_in_eighths
time_from_measure_start = start_time % N_EIGHTHS_PER_MEASURE
duration_in_measures = (end_time - start_time) / N_EIGHTHS_PER_MEASURE
if duration_in_measures == 1.0 and time_from_measure_start > 0:
filled_measure_share = time_from_measure_start / N_EIGHTHS_PER_MEASURE
remaining_duration = int(round(1 / (1 - filled_measure_share)))
remaining_note = f"{pitch_class}{octave_info}{remaining_duration}~"
left_over_bar_duration = int(round(1 / filled_measure_share))
left_over_note = f"{pitch_class}{octave_info}{left_over_bar_duration}"
return f"{remaining_note} {left_over_note}"
else:
duration = int(round((1 / duration_in_measures)))
note = f"{pitch_class}{octave_info}{duration}"
return note
def combine_lilypond_voices(
counterpoint_voice: str,
cantus_firmus_voice: str,
is_counterpoint_above: bool,
counterpoint_start_pause_in_eighths: int
) -> List[str]:
"""
Sort Lilypond voices and add delay to counterpoint voice if needed.
:param counterpoint_voice:
Lilypond representation of counterpoint line (without pauses)
:param cantus_firmus_voice:
Lilypond representation of cantus firmus line
:param is_counterpoint_above:
indicator whether counterpoint is written above cantus firmus
:param counterpoint_start_pause_in_eighths:
duration of pause that opens counterpoint line (in eighths of measure)
:return:
combined Lilypond representations
"""
if counterpoint_start_pause_in_eighths > 0:
pause_duration = int(round(
N_EIGHTHS_PER_MEASURE / counterpoint_start_pause_in_eighths
))
pause = f'r{pause_duration}'
counterpoint_voice = pause + ' ' + counterpoint_voice
if is_counterpoint_above:
return [counterpoint_voice, cantus_firmus_voice]
else:
return [cantus_firmus_voice, counterpoint_voice]
def create_lilypond_file_from_piece(
piece: 'rlmusician.environment.Piece',
output_path: str
) -> None:
"""
Create text file in format of Lilypond sheet music editor.
:param piece:
musical piece
:param output_path:
path where resulting file is going to be saved
:return:
None
"""
template = make_lilypond_template(piece.tonic, piece.scale_type)
lilypond_voices = {}
melodic_lines = {
'counterpoint': piece.counterpoint,
'cantus_firmus': piece.cantus_firmus
}
for line_id, melodic_line in melodic_lines.items():
lilypond_voice = []
for line_element in melodic_line:
note = convert_to_lilypond_note(line_element)
lilypond_voice.append(note)
lilypond_voice = " ".join(lilypond_voice)
lilypond_voices[line_id] = lilypond_voice
lilypond_voices = combine_lilypond_voices(
lilypond_voices['counterpoint'],
lilypond_voices['cantus_firmus'],
piece.is_counterpoint_above,
piece.counterpoint_specifications['start_pause_in_eighths']
)
result = template.format(*lilypond_voices)
with open(output_path, 'w') as out_file:
out_file.write(result)
def create_pdf_sheet_music_with_lilypond(
lilypond_path: str
) -> None: # pragma: no cover
"""
Create PDF file with sheet music.
:param lilypond_path:
path to a text file in Lilypond format
:return:
None:
"""
dir_path, filename = os.path.split(lilypond_path)
bash_command = f"lilypond {filename}"
try:
process = subprocess.Popen(
bash_command.split(),
cwd=dir_path,
stdout=subprocess.PIPE
)
process.communicate()
except Exception:
print("Rendering sheet music to PDF failed. Do you have Lilypond?")
print(traceback.format_exc()) | 0.816589 | 0.249859 |
__license__ = """
GoLismero 2.0 - The web knife - Copyright (C) 2011-2014
Golismero project site: https://github.com/golismero
Golismero project mail: <EMAIL>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from golismero.api.config import Config
from golismero.api.data import discard_data
from golismero.api.data.resource.domain import Domain
from golismero.api.data.resource.email import Email
from golismero.api.data.resource.ip import IP
from golismero.api.external import get_tools_folder
from golismero.api.logger import Logger
from golismero.api.plugin import TestingPlugin
import os, os.path
import socket
import StringIO
import sys
import traceback
import warnings
# Import theHarvester as a library.
cwd = os.path.abspath(get_tools_folder())
cwd = os.path.join(cwd, "theHarvester")
sys.path.insert(0, cwd)
try:
import discovery
from discovery import * #noqa
finally:
sys.path.remove(cwd)
del cwd
#------------------------------------------------------------------------------
class HarvesterPlugin(TestingPlugin):
"""
Integration with
`theHarvester <https://github.com/MarioVilas/theHarvester/>`_.
"""
# Supported theHarvester modules.
SUPPORTED = (
"google", "bing", "linkedin", "dogpile", #"pgp"
)
#--------------------------------------------------------------------------
def get_accepted_types(self):
return [Domain]
#--------------------------------------------------------------------------
def run(self, info):
# Get the search parameters.
word = info.hostname
limit = 100
try:
limit = int(Config.plugin_config.get("limit", str(limit)), 0)
except ValueError:
pass
# Search every supported engine.
total = float(len(self.SUPPORTED))
all_emails, all_hosts = set(), set()
for step, engine in enumerate(self.SUPPORTED):
try:
Logger.log_verbose("Searching keyword %r in %s" % (word, engine))
self.update_status(progress=float(step * 80) / total)
emails, hosts = self.search(engine, word, limit)
except Exception, e:
t = traceback.format_exc()
Logger.log_error(str(e))
Logger.log_error_more_verbose(t)
continue
all_emails.update(address.lower() for address in emails if address)
all_hosts.update(name.lower() for name in hosts if name)
self.update_status(progress=80)
Logger.log_more_verbose("Search complete for keyword %r" % word)
# Adapt the data into our model.
results = []
# Email addresses.
emails_found = set()
emails_count = 0
for address in all_emails:
if "..." in address: # known bug in theHarvester
continue
while address and not address[0].isalnum():
address = address[1:] # known bug in theHarvester
while address and not address[-1].isalnum():
address = address[:-1]
if not address:
continue
if not "@" in address:
continue
if address in emails_found:
continue
emails_found.add(address)
try:
data = Email(address)
except Exception, e:
warnings.warn("Cannot parse email address: %r" % address)
continue
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
in_scope = data.is_in_scope()
if in_scope:
data.add_resource(info)
results.append(data)
all_hosts.add(data.hostname)
emails_count += 1
else:
Logger.log_more_verbose(
"Email address out of scope: %s" % address)
discard_data(data)
# Hostnames.
visited = set()
total = float(len(all_hosts))
hosts_count = 0
ips_count = 0
for step, name in enumerate(all_hosts):
while name and not name[0].isalnum(): # known bug in theHarvester
name = name[1:]
while name and not name[-1].isalnum():
name = name[:-1]
if not name:
continue
visited.add(name)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
in_scope = name in Config.audit_scope
if not in_scope:
Logger.log_more_verbose("Hostname out of scope: %s" % name)
continue
try:
self.update_status(progress=(float(step * 20) / total) + 80.0)
Logger.log_more_verbose("Checking hostname: %s" % name)
real_name, aliaslist, addresslist = \
socket.gethostbyname_ex(name)
except socket.error:
continue
all_names = set()
all_names.add(name)
all_names.add(real_name)
all_names.update(aliaslist)
for name in all_names:
if name and name not in visited:
visited.add(name)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
in_scope = name in Config.audit_scope
if not in_scope:
Logger.log_more_verbose(
"Hostname out of scope: %s" % name)
continue
data = Domain(name)
data.add_resource(info)
results.append(data)
hosts_count += 1
for ip in addresslist:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
in_scope = ip in Config.audit_scope
if not in_scope:
Logger.log_more_verbose(
"IP address out of scope: %s" % ip)
continue
d = IP(ip)
data.add_resource(d)
results.append(d)
ips_count += 1
self.update_status(progress=100.0)
text = "Found %d emails, %d hostnames and %d IP addresses " \
"for keyword %r" % (emails_count, hosts_count, ips_count, word)
if len(results) > 0:
Logger.log(text)
else:
Logger.log_more_verbose(text)
# Return the data.
return results
#--------------------------------------------------------------------------
@staticmethod
def search(engine, word, limit = 100):
"""
Run a theHarvester search on the given engine.
:param engine: Search engine.
:type engine: str
:param word: Word to search for.
:type word: str
:param limit: Maximum number of results.
Its exact meaning may depend on the search engine.
:type limit: int
:returns: All email addresses, hostnames and usernames collected.
:rtype: tuple(list(str), list(str), list(str))
"""
Logger.log_more_verbose("Searching on: %s" % engine)
# Get the search class.
search_mod = getattr(discovery, "%ssearch" % engine)
search_fn = getattr(search_mod, "search_%s" % engine)
# Run the search, hiding all the prints.
fd = StringIO.StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = fd, fd
class Options:
pass
options = Options()
options.word = word
options.limit = limit
options.start = 0
search = search_fn(word, options)
search.process()
finally:
sys.stdout, sys.stderr = old_out, old_err
# Extract the results.
emails, hosts = [], []
results = search.get_results()
if hasattr(results, "emails"):
try:
emails = results.emails
except Exception, e:
t = traceback.format_exc()
Logger.log_error(str(e))
Logger.log_error_more_verbose(t)
if hasattr(results, "hostnames"):
try:
hosts = results.hostnames
except Exception, e:
t = traceback.format_exc()
Logger.log_error(str(e))
Logger.log_error_more_verbose(t)
Logger.log_verbose(
"Found %d emails and %d hostnames on %s for domain %s" %
(len(emails), len(hosts), engine, word)
)
# Return the results.
return emails, hosts | Dangerous/Golismero/plugins/testing/recon/theharvester.py | __license__ = """
GoLismero 2.0 - The web knife - Copyright (C) 2011-2014
Golismero project site: https://github.com/golismero
Golismero project mail: <EMAIL>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from golismero.api.config import Config
from golismero.api.data import discard_data
from golismero.api.data.resource.domain import Domain
from golismero.api.data.resource.email import Email
from golismero.api.data.resource.ip import IP
from golismero.api.external import get_tools_folder
from golismero.api.logger import Logger
from golismero.api.plugin import TestingPlugin
import os, os.path
import socket
import StringIO
import sys
import traceback
import warnings
# Import theHarvester as a library.
cwd = os.path.abspath(get_tools_folder())
cwd = os.path.join(cwd, "theHarvester")
sys.path.insert(0, cwd)
try:
import discovery
from discovery import * #noqa
finally:
sys.path.remove(cwd)
del cwd
#------------------------------------------------------------------------------
class HarvesterPlugin(TestingPlugin):
"""
Integration with
`theHarvester <https://github.com/MarioVilas/theHarvester/>`_.
"""
# Supported theHarvester modules.
SUPPORTED = (
"google", "bing", "linkedin", "dogpile", #"pgp"
)
#--------------------------------------------------------------------------
def get_accepted_types(self):
return [Domain]
#--------------------------------------------------------------------------
def run(self, info):
# Get the search parameters.
word = info.hostname
limit = 100
try:
limit = int(Config.plugin_config.get("limit", str(limit)), 0)
except ValueError:
pass
# Search every supported engine.
total = float(len(self.SUPPORTED))
all_emails, all_hosts = set(), set()
for step, engine in enumerate(self.SUPPORTED):
try:
Logger.log_verbose("Searching keyword %r in %s" % (word, engine))
self.update_status(progress=float(step * 80) / total)
emails, hosts = self.search(engine, word, limit)
except Exception, e:
t = traceback.format_exc()
Logger.log_error(str(e))
Logger.log_error_more_verbose(t)
continue
all_emails.update(address.lower() for address in emails if address)
all_hosts.update(name.lower() for name in hosts if name)
self.update_status(progress=80)
Logger.log_more_verbose("Search complete for keyword %r" % word)
# Adapt the data into our model.
results = []
# Email addresses.
emails_found = set()
emails_count = 0
for address in all_emails:
if "..." in address: # known bug in theHarvester
continue
while address and not address[0].isalnum():
address = address[1:] # known bug in theHarvester
while address and not address[-1].isalnum():
address = address[:-1]
if not address:
continue
if not "@" in address:
continue
if address in emails_found:
continue
emails_found.add(address)
try:
data = Email(address)
except Exception, e:
warnings.warn("Cannot parse email address: %r" % address)
continue
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
in_scope = data.is_in_scope()
if in_scope:
data.add_resource(info)
results.append(data)
all_hosts.add(data.hostname)
emails_count += 1
else:
Logger.log_more_verbose(
"Email address out of scope: %s" % address)
discard_data(data)
# Hostnames.
visited = set()
total = float(len(all_hosts))
hosts_count = 0
ips_count = 0
for step, name in enumerate(all_hosts):
while name and not name[0].isalnum(): # known bug in theHarvester
name = name[1:]
while name and not name[-1].isalnum():
name = name[:-1]
if not name:
continue
visited.add(name)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
in_scope = name in Config.audit_scope
if not in_scope:
Logger.log_more_verbose("Hostname out of scope: %s" % name)
continue
try:
self.update_status(progress=(float(step * 20) / total) + 80.0)
Logger.log_more_verbose("Checking hostname: %s" % name)
real_name, aliaslist, addresslist = \
socket.gethostbyname_ex(name)
except socket.error:
continue
all_names = set()
all_names.add(name)
all_names.add(real_name)
all_names.update(aliaslist)
for name in all_names:
if name and name not in visited:
visited.add(name)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
in_scope = name in Config.audit_scope
if not in_scope:
Logger.log_more_verbose(
"Hostname out of scope: %s" % name)
continue
data = Domain(name)
data.add_resource(info)
results.append(data)
hosts_count += 1
for ip in addresslist:
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
in_scope = ip in Config.audit_scope
if not in_scope:
Logger.log_more_verbose(
"IP address out of scope: %s" % ip)
continue
d = IP(ip)
data.add_resource(d)
results.append(d)
ips_count += 1
self.update_status(progress=100.0)
text = "Found %d emails, %d hostnames and %d IP addresses " \
"for keyword %r" % (emails_count, hosts_count, ips_count, word)
if len(results) > 0:
Logger.log(text)
else:
Logger.log_more_verbose(text)
# Return the data.
return results
#--------------------------------------------------------------------------
@staticmethod
def search(engine, word, limit = 100):
"""
Run a theHarvester search on the given engine.
:param engine: Search engine.
:type engine: str
:param word: Word to search for.
:type word: str
:param limit: Maximum number of results.
Its exact meaning may depend on the search engine.
:type limit: int
:returns: All email addresses, hostnames and usernames collected.
:rtype: tuple(list(str), list(str), list(str))
"""
Logger.log_more_verbose("Searching on: %s" % engine)
# Get the search class.
search_mod = getattr(discovery, "%ssearch" % engine)
search_fn = getattr(search_mod, "search_%s" % engine)
# Run the search, hiding all the prints.
fd = StringIO.StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = fd, fd
class Options:
pass
options = Options()
options.word = word
options.limit = limit
options.start = 0
search = search_fn(word, options)
search.process()
finally:
sys.stdout, sys.stderr = old_out, old_err
# Extract the results.
emails, hosts = [], []
results = search.get_results()
if hasattr(results, "emails"):
try:
emails = results.emails
except Exception, e:
t = traceback.format_exc()
Logger.log_error(str(e))
Logger.log_error_more_verbose(t)
if hasattr(results, "hostnames"):
try:
hosts = results.hostnames
except Exception, e:
t = traceback.format_exc()
Logger.log_error(str(e))
Logger.log_error_more_verbose(t)
Logger.log_verbose(
"Found %d emails and %d hostnames on %s for domain %s" %
(len(emails), len(hosts), engine, word)
)
# Return the results.
return emails, hosts | 0.376967 | 0.061537 |
from __future__ import print_function
import datetime
import pickle
import os.path
import argparse
import hy
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from dateutil.parser import parse as dateparse
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
def events_from_ics(calendar_names, start_time, n):
import recurring_ical_events
import requests
from icalendar import Calendar, Event
event_objs=[]
print(calendar_names)
for name in calendar_names:
r=requests.get(name)
cal=Calendar.from_ical(r.content)
calname=cal['X-WR-CALNAME']
print(f'Getting events for calendar with name {calname}...')
events=recurring_ical_events.of(cal).between(start_time,datetime.datetime.now())
for event in events:
start = event['DTSTART'].dt.isoformat()
end = event['DTEND'].dt.isoformat()
print(start, event['SUMMARY'])
event_objs.append({'start': start,
'end': end,
'summary': event['SUMMARY'],
'calendar_name': calname,
'fullname': calname + '/' + event['SUMMARY']})
return event_objs
def events_from_calendars(calendar_names, start_time, n):
# Much of this function is taken directly from Google Calendar quickstart documentation
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('calendar', 'v3', credentials=creds)
event_objs = []
# Call the Calendar API
print('Getting calendars ...')
all_calendars = service.calendarList().list().execute()["items"]
start_time_formatted = start_time.isoformat() + 'Z'
print(start_time_formatted)
for name in calendar_names:
calendar_id = None
for cal in all_calendars:
if cal["summary"] == name:
calendar_id = cal["id"]
print(f'Getting events for calendar with name {name} and id {calendar_id}...')
events_result = service.events().list(calendarId=calendar_id,
timeMin=start_time_formatted,
maxResults=n,
singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
end = event['end'].get('dateTime', event['end'].get('date'))
print(start, event['summary'])
event_objs.append({'start': start,
'end': end,
'summary': event['summary'],
'calendar_name': name,
'fullname': name + '/' + event['summary']})
return event_objs | download.py | from __future__ import print_function
import datetime
import pickle
import os.path
import argparse
import hy
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from dateutil.parser import parse as dateparse
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
def events_from_ics(calendar_names, start_time, n):
import recurring_ical_events
import requests
from icalendar import Calendar, Event
event_objs=[]
print(calendar_names)
for name in calendar_names:
r=requests.get(name)
cal=Calendar.from_ical(r.content)
calname=cal['X-WR-CALNAME']
print(f'Getting events for calendar with name {calname}...')
events=recurring_ical_events.of(cal).between(start_time,datetime.datetime.now())
for event in events:
start = event['DTSTART'].dt.isoformat()
end = event['DTEND'].dt.isoformat()
print(start, event['SUMMARY'])
event_objs.append({'start': start,
'end': end,
'summary': event['SUMMARY'],
'calendar_name': calname,
'fullname': calname + '/' + event['SUMMARY']})
return event_objs
def events_from_calendars(calendar_names, start_time, n):
# Much of this function is taken directly from Google Calendar quickstart documentation
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('calendar', 'v3', credentials=creds)
event_objs = []
# Call the Calendar API
print('Getting calendars ...')
all_calendars = service.calendarList().list().execute()["items"]
start_time_formatted = start_time.isoformat() + 'Z'
print(start_time_formatted)
for name in calendar_names:
calendar_id = None
for cal in all_calendars:
if cal["summary"] == name:
calendar_id = cal["id"]
print(f'Getting events for calendar with name {name} and id {calendar_id}...')
events_result = service.events().list(calendarId=calendar_id,
timeMin=start_time_formatted,
maxResults=n,
singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
end = event['end'].get('dateTime', event['end'].get('date'))
print(start, event['summary'])
event_objs.append({'start': start,
'end': end,
'summary': event['summary'],
'calendar_name': name,
'fullname': name + '/' + event['summary']})
return event_objs | 0.324449 | 0.107227 |
from migen import *
import math
from third_party import wishbone as wb
class IOControl(Module):
def __init__(self, pins, config, bus=None, debug_bus=None):
if bus is None:
self.bus = wb.Interface(data_width=32, adr_width=32)
else:
self.bus = bus
if debug_bus is None:
self.debug_bus = wb.Interface(data_width=32, adr_width=32)
else:
self.debug_bus = debug_bus
self.irq = Signal()
self.sync += self.irq.eq(0)
io = []
assert 0 < len(config) and len(config) < 256
"""
Pad naming: io0, io1, io2, ...
Config:
[
{
index: 0, # must match index of pin in array
name: "", # optional
mode: "standard/passthrough/passthrough-direct",
sync: True/False,
options: [ # Only for standard-mode
(ind, name, i, o, oe), # ind must not be zero
(ind, name, i, o, oe),
(ind, name, i, o, oe),
... up to 16
],
passthrough: (i, o, oe) # Only for passthrough-mode
}
]
state = {4'b0, type[1:0], actual_enable, actual_select[3:0], actual_irqmode[1:0], actual_oe, actual_out, actual_in}
Dbg reg: {15'b0, 1'b0, state[15:0]}
CPU reg: {state[15:0], 1'b0, enable, select[3:0], irqmode[1:0], 5'b0, gpio_oe, gpio_out, gpio_in}
Data:
- GPIO in
- GPIO out
- GPIO oe
- enable
- select[3:0]
- IRQ mode[1:0] - 0 = none, 1 = rising, 2 = falling
State:
- Actual out
- Actual in
- Actual oe
- Actual enable
- Actual select[3:0]
- Actual irq mode[1:0]
- type[1:0] - 0 = standard, 1 = passthrough, 2 = passthrough-silent
"""
# Set up I/O
for pin_ind, pin in enumerate(config):
assert pin["index"] == pin_ind
mode = pin["mode"]
assert mode in ["standard", "passthrough", "passthrough-direct"]
if mode != "standard":
assert "options" not in pin or len(pin["options"]) == 0
assert "passthrough" in pin
pad = pins["io{}".format(pin_ind)]
ind = Constant(pin_ind, bits_sign=8)
if pin["sync"]:
ff1 = Signal(reset_less=True)
ff2 = Signal(reset_less=True)
pad_i = Signal(reset_less=True)
self.sync += [
ff1.eq(pad.i),
ff2.eq(ff1),
pad_i.eq(ff2),
]
else:
pad_i = pad.i
pad_o = pad.o
pad_oe = pad.oe
if mode == "standard":
typ = Constant(0, bits_sign=2)
elif mode == "passthrough":
typ = Constant(1, bits_sign=2)
elif mode == "passthrough-direct":
typ = Constant(2, bits_sign=2)
last = Signal(reset=0)
self.sync += last.eq(pad_i)
rising = ~pad_oe & pad_i & ~last
falling = ~pad_oe & last & ~pad_i
gpio_in = Signal(reset=0)
gpio_out = Signal(reset=0)
gpio_oe = Signal(reset=0)
irqmode = Signal(2, reset=0)
select = Signal(4, reset=0)
enable = Signal(reset=0)
if mode == "passthrough-direct":
state = Cat(Constant(0, bits_sign=3), irqmode, select, enable, typ, Constant(0, bits_sign=4))
else:
state = Cat(pad_i, pad_o, pad_oe, irqmode, select, enable, typ, Constant(0, bits_sign=4))
assert len(state) == 16
dbg_reg = Cat(state, Constant(0, bits_sign=16))
assert len(dbg_reg) == 32
cpu_reg = Cat(gpio_in, gpio_out, gpio_oe, Constant(0, bits_sign=5), irqmode, select, enable, Constant(0, bits_sign=1), state)
assert len(cpu_reg) == 32
if mode == "passthrough-direct" or mode == "passthrough":
self.comb += [
pin["passthrough"][0].eq(pad_i),
pad_o.eq(pin["passthrough"][1]),
pad_oe.eq(pin["passthrough"][2]),
]
else:
# Set up standard I/O multiplexing
options = [x for x in pin["options"]]
assert not any([x[0] == 0 for x in options])
#options.append((0, "gpio", gpio_in, gpio_out, gpio_oe))
cases = {}
cases["default"] = [
pad_o.eq(gpio_out),
pad_oe.eq(gpio_oe),
]
self.comb += gpio_in.eq(pad_i)
for opt_ind, name, i, o, oe in options:
self.comb += i.eq(pad_i)
cases[opt_ind] = [
pad_o.eq(o),
pad_oe.eq(oe),
]
self.comb += [
If(~enable, pad_oe.eq(0), pad_o.eq(0)).
Else(Case(select, cases))
]
self.sync += [
If(rising & irqmode == 1, self.irq.eq(1)),
If(falling & irqmode == 2, self.irq.eq(1))
]
assert pin_ind == len(io)
io.append({
"index": pin_ind,
"gpio_in": gpio_in,
"gpio_out": gpio_out,
"gpio_oe": gpio_oe,
"enable": enable,
"select": select,
"irqmode": irqmode,
"cpu_reg": cpu_reg,
"dbg_reg": dbg_reg,
})
# Main bus access
# CPU reg: {state[15:0], 1'b0, enable, select[3:0], irqmode[1:0], 5'b0, gpio_oe, gpio_out, gpio_in}
self.sync += [
self.bus.ack.eq(0),
self.bus.err.eq(0),
If(self.bus.stb & self.bus.cyc & ~self.bus.ack,
self.bus.ack.eq(1),
*[If((self.bus.adr >> 2) == port["index"],
self.bus.dat_r.eq(port["cpu_reg"]),
If(self.bus.we & self.bus.sel[0],
port["gpio_out"].eq(self.bus.dat_w[1]),
port["gpio_oe"].eq(self.bus.dat_w[2])),
If(self.bus.we & self.bus.sel[1],
port["irqmode"].eq(self.bus.dat_w[8:10]),
port["select"].eq(self.bus.dat_w[10:14]),
port["enable"].eq(self.bus.dat_w[14]))
) for port in io]
)
]
# Debug bus access
self.sync += [
self.debug_bus.ack.eq(0),
self.debug_bus.err.eq(0),
If(self.debug_bus.stb & self.debug_bus.cyc & ~self.debug_bus.ack,
self.debug_bus.ack.eq(1),
*[If((self.debug_bus.adr >> 2) == port["index"],
self.debug_bus.dat_r.eq(port["dbg_reg"]),
) for port in io]
)
] | soc/rtl/io_control.py | from migen import *
import math
from third_party import wishbone as wb
class IOControl(Module):
def __init__(self, pins, config, bus=None, debug_bus=None):
if bus is None:
self.bus = wb.Interface(data_width=32, adr_width=32)
else:
self.bus = bus
if debug_bus is None:
self.debug_bus = wb.Interface(data_width=32, adr_width=32)
else:
self.debug_bus = debug_bus
self.irq = Signal()
self.sync += self.irq.eq(0)
io = []
assert 0 < len(config) and len(config) < 256
"""
Pad naming: io0, io1, io2, ...
Config:
[
{
index: 0, # must match index of pin in array
name: "", # optional
mode: "standard/passthrough/passthrough-direct",
sync: True/False,
options: [ # Only for standard-mode
(ind, name, i, o, oe), # ind must not be zero
(ind, name, i, o, oe),
(ind, name, i, o, oe),
... up to 16
],
passthrough: (i, o, oe) # Only for passthrough-mode
}
]
state = {4'b0, type[1:0], actual_enable, actual_select[3:0], actual_irqmode[1:0], actual_oe, actual_out, actual_in}
Dbg reg: {15'b0, 1'b0, state[15:0]}
CPU reg: {state[15:0], 1'b0, enable, select[3:0], irqmode[1:0], 5'b0, gpio_oe, gpio_out, gpio_in}
Data:
- GPIO in
- GPIO out
- GPIO oe
- enable
- select[3:0]
- IRQ mode[1:0] - 0 = none, 1 = rising, 2 = falling
State:
- Actual out
- Actual in
- Actual oe
- Actual enable
- Actual select[3:0]
- Actual irq mode[1:0]
- type[1:0] - 0 = standard, 1 = passthrough, 2 = passthrough-silent
"""
# Set up I/O
for pin_ind, pin in enumerate(config):
assert pin["index"] == pin_ind
mode = pin["mode"]
assert mode in ["standard", "passthrough", "passthrough-direct"]
if mode != "standard":
assert "options" not in pin or len(pin["options"]) == 0
assert "passthrough" in pin
pad = pins["io{}".format(pin_ind)]
ind = Constant(pin_ind, bits_sign=8)
if pin["sync"]:
ff1 = Signal(reset_less=True)
ff2 = Signal(reset_less=True)
pad_i = Signal(reset_less=True)
self.sync += [
ff1.eq(pad.i),
ff2.eq(ff1),
pad_i.eq(ff2),
]
else:
pad_i = pad.i
pad_o = pad.o
pad_oe = pad.oe
if mode == "standard":
typ = Constant(0, bits_sign=2)
elif mode == "passthrough":
typ = Constant(1, bits_sign=2)
elif mode == "passthrough-direct":
typ = Constant(2, bits_sign=2)
last = Signal(reset=0)
self.sync += last.eq(pad_i)
rising = ~pad_oe & pad_i & ~last
falling = ~pad_oe & last & ~pad_i
gpio_in = Signal(reset=0)
gpio_out = Signal(reset=0)
gpio_oe = Signal(reset=0)
irqmode = Signal(2, reset=0)
select = Signal(4, reset=0)
enable = Signal(reset=0)
if mode == "passthrough-direct":
state = Cat(Constant(0, bits_sign=3), irqmode, select, enable, typ, Constant(0, bits_sign=4))
else:
state = Cat(pad_i, pad_o, pad_oe, irqmode, select, enable, typ, Constant(0, bits_sign=4))
assert len(state) == 16
dbg_reg = Cat(state, Constant(0, bits_sign=16))
assert len(dbg_reg) == 32
cpu_reg = Cat(gpio_in, gpio_out, gpio_oe, Constant(0, bits_sign=5), irqmode, select, enable, Constant(0, bits_sign=1), state)
assert len(cpu_reg) == 32
if mode == "passthrough-direct" or mode == "passthrough":
self.comb += [
pin["passthrough"][0].eq(pad_i),
pad_o.eq(pin["passthrough"][1]),
pad_oe.eq(pin["passthrough"][2]),
]
else:
# Set up standard I/O multiplexing
options = [x for x in pin["options"]]
assert not any([x[0] == 0 for x in options])
#options.append((0, "gpio", gpio_in, gpio_out, gpio_oe))
cases = {}
cases["default"] = [
pad_o.eq(gpio_out),
pad_oe.eq(gpio_oe),
]
self.comb += gpio_in.eq(pad_i)
for opt_ind, name, i, o, oe in options:
self.comb += i.eq(pad_i)
cases[opt_ind] = [
pad_o.eq(o),
pad_oe.eq(oe),
]
self.comb += [
If(~enable, pad_oe.eq(0), pad_o.eq(0)).
Else(Case(select, cases))
]
self.sync += [
If(rising & irqmode == 1, self.irq.eq(1)),
If(falling & irqmode == 2, self.irq.eq(1))
]
assert pin_ind == len(io)
io.append({
"index": pin_ind,
"gpio_in": gpio_in,
"gpio_out": gpio_out,
"gpio_oe": gpio_oe,
"enable": enable,
"select": select,
"irqmode": irqmode,
"cpu_reg": cpu_reg,
"dbg_reg": dbg_reg,
})
# Main bus access
# CPU reg: {state[15:0], 1'b0, enable, select[3:0], irqmode[1:0], 5'b0, gpio_oe, gpio_out, gpio_in}
self.sync += [
self.bus.ack.eq(0),
self.bus.err.eq(0),
If(self.bus.stb & self.bus.cyc & ~self.bus.ack,
self.bus.ack.eq(1),
*[If((self.bus.adr >> 2) == port["index"],
self.bus.dat_r.eq(port["cpu_reg"]),
If(self.bus.we & self.bus.sel[0],
port["gpio_out"].eq(self.bus.dat_w[1]),
port["gpio_oe"].eq(self.bus.dat_w[2])),
If(self.bus.we & self.bus.sel[1],
port["irqmode"].eq(self.bus.dat_w[8:10]),
port["select"].eq(self.bus.dat_w[10:14]),
port["enable"].eq(self.bus.dat_w[14]))
) for port in io]
)
]
# Debug bus access
self.sync += [
self.debug_bus.ack.eq(0),
self.debug_bus.err.eq(0),
If(self.debug_bus.stb & self.debug_bus.cyc & ~self.debug_bus.ack,
self.debug_bus.ack.eq(1),
*[If((self.debug_bus.adr >> 2) == port["index"],
self.debug_bus.dat_r.eq(port["dbg_reg"]),
) for port in io]
)
] | 0.396535 | 0.347094 |
import rospy
import numpy as np
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from std_msgs.msg import String
import tf_conversions
import tf2_ros
class CommandCenter(object):
def __init__(self):
self.pub_vel = rospy.Publisher("cmd_vel", Twist, queue_size = 10)
self.pub_reset = rospy.Publisher("command", String, queue_size = 1) #odometry_odometry_handler_collect_data.py subscribes to this topic
self.rate = rospy.Rate(20.0)
self.resetAfter = False
self.linear_x = 0.0
self.angular_z = 0.0
self.desired_distance = 0.0
self.desired_angle = 0.0
self.data = []
self.tfBuffer = tf2_ros.Buffer()
self.listener = tf2_ros.TransformListener(self.tfBuffer)
def publish_vel(self, twist_msg):
self.pub_vel.publish(twist_msg)
def publish_reset(self):
while not rospy.wait_for_message('odom', Odometry, timeout=1.0).pose.pose.position.x == 0.0:
self.pub_reset.publish("reset")
self.rate.sleep()
def write_to_csv(self):
np.savetxt('data.csv', self.data, fmt="%1.3f", delimiter=",", header='x,y', comments='') #the comments argument is needed because by default the header string will be preced by a # since the header, for numpy, is a comment
def createTwistMsg(self, x, z):
twist_msg = Twist()
twist_msg.linear.x = x
twist_msg.angular.z = z
return twist_msg
def translate(self):
available = False
while not available and not rospy.is_shutdown():
if self.tfBuffer.can_transform('odom', 'base_link', rospy.Time()):
available = True
start_transform = self.tfBuffer.lookup_transform('odom', 'base_link', rospy.Time())
start_xpos = start_transform.transform.translation.x
start_ypos = start_transform.transform.translation.y
done = False
while not done and not rospy.is_shutdown():
self.publish_vel(self.createTwistMsg(self.linear_x, 0.0))
self.rate.sleep()
try:
current_transform = self.tfBuffer.lookup_transform('odom', 'base_link', rospy.Time())
except (tf2_ros.LookupException, tf2_ros.ConnectivityException, tf2_ros.ExtrapolationException):
self.rate.sleep()
continue
current_xpos = current_transform.transform.translation.x
current_ypos = current_transform.transform.translation.y
if abs(current_xpos - start_xpos) >= self.desired_distance or abs(current_ypos - start_ypos) >= self.desired_distance:
self.publish_vel(self.createTwistMsg(0.0, 0.0))
if self.resetAfter:
msg = rospy.wait_for_message('odom', Odometry, timeout=1.0) # In theory we could also just use the current_transform
self.published_position.append([msg.pose.pose.position.x, msg.pose.pose.position.y])
self.publish_reset()
done = True
def rotate(self):
#checking if rotating clockwise or counter clockwise
if self.angular_z > 0:
clockwise = False
else:
clockwise = True
#checking if transform is available
available = False
while not available and not rospy.is_shutdown():
if self.tfBuffer.can_transform('odom', 'base_link', rospy.Time()):
available = True
#getting start transform
start_transform = self.tfBuffer.lookup_transform('odom', 'base_link', rospy.Time())
#getting the angle from the transform
start_angle = tf_conversions.transformations.euler_from_quaternion([start_transform.transform.rotation.x, start_transform.transform.rotation.y, start_transform.transform.rotation.z, start_transform.transform.rotation.w])[2]
#changing interval from [-pi, pi] to [0, 2*pi]
if not clockwise and start_angle < 0:
start_angle = start_angle + 2*np.pi
elif clockwise and start_angle > 0:
start_angle = 2*np.pi - start_angle
done = False
while not done and not rospy.is_shutdown():
#publishing twist message with specified angular velocity
self.publish_vel(self.createTwistMsg(0.0, self.angular_z))
self.rate.sleep()
#getting current transform
try:
current_transform = self.tfBuffer.lookup_transform('odom', 'base_link', rospy.Time())
except (tf2_ros.LookupException, tf2_ros.ConnectivityException, tf2_ros.ExtrapolationException):
self.rate.sleep()
continue
#getting the angle from the transform
current_angle = tf_conversions.transformations.euler_from_quaternion([current_transform.transform.rotation.x, current_transform.transform.rotation.y, current_transform.transform.rotation.z, current_transform.transform.rotation.w])[2]
#changing interval from [-pi, pi] to [0, 2*pi]
if not clockwise and current_angle < 0:
current_angle = current_angle + 2*np.pi
elif clockwise and current_angle > 0:
current_angle = current_angle - 2*np.pi
#calculating the angle between the transforms and converting it to degrees
relative_angle = abs(current_angle - start_angle) * 180 / np.pi
print('start_angle: {} current angle: {} angle_turned: {}'.format(start_angle*180/np.pi, current_angle*180/np.pi, relative_angle))
if relative_angle >= self.desired_angle:
self.publish_vel(self.createTwistMsg(0.0, 0.0))
done = True
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
if __name__ == "__main__":
rospy.init_node('send_twist_msgs_node', anonymous = False)
comc = CommandCenter()
print(bcolors.OKBLUE + 'Type "help" for all possible instructions.' + bcolors.ENDC)
speeds, limits = False, False
while not rospy.is_shutdown():
#checking if speeds and desired distance/angle have been set
if not speeds and not limits:
print(bcolors.FAIL + 'PLEASE SET SPEEDS AND DISTANCE/ANGLE WITH "setSpeeds" and "setLimits"' + bcolors.ENDC)
elif not speeds:
print(bcolors.FAIL + 'PLEASE SET SPEEDS with "setSpeeds"' + bcolors.ENDC)
elif not limits:
print(bcolors.FAIL + 'PLEASE SET DESIRED DISTANCE AND ANGLE WITH "setLimits"' + bcolors.ENDC)
#giving a warning if odom topic gets reset
if comc.resetAfter:
print(bcolors.WARNING + 'REMINDER: odom topic values will be reset to zero after a translation or rotation' + bcolors.ENDC)
#getting user input
user_input = raw_input('Give instruction: ')
#checking what the user input is and acting accordingly
if user_input == 'setSpeeds':
speed_vel = raw_input('Give linear velocity (in m/s) and rotational velocity (in rad/s) separated by a comma: ')
speed_vel = speed_vel.split(',')
try:
comc.linear_x = float(speed_vel[0])
comc.angular_z = float(speed_vel[1])
speeds = True
print(bcolors.OKGREEN + 'Set linear_x to: {} m/s and angular_z to: {} rad/s'.format(speed_vel[0], speed_vel[1]) + bcolors.ENDC)
except IndexError as e:
print(bcolors.FAIL + 'IndexError: ' + str(e) + bcolors.ENDC)
if user_input == 'setLimits':
dist_ang = raw_input('Give desired distance (in m) and desired angle (in degrees) seperated by a comma: ')
dist_ang = dist_ang.split(',')
try:
comc.desired_distance = float(dist_ang[0])
comc.desired_angle = float(dist_ang[1])
limits = True
print(bcolors.OKGREEN + 'Set desired_distance to: {} m and desired_angle to: {} degrees'.format(dist_ang[0], dist_ang[1]) + bcolors.ENDC)
except IndexError as e:
print(bcolors.FAIL + 'IndexError: ' + str(e) + bcolors.ENDC)
if user_input == 'toggleResetAfter':
if comc.resetAfter:
comc.resetAfter = False
else:
comc.resetAfter = True
print(bcolors.OKGREEN + 'resetAfter has been set to: {}'.format(comc.resetAfter) + bcolors.ENDC)
if user_input == 'publishReset':
comc.publish_reset()
if user_input == 'go':
comc.translate()
if user_input == 'rotate':
comc.rotate()
if user_input == 'write':
comc.write_to_csv()
if user_input == 'stop':
rospy.signal_shutdown("typed stop")
if user_input == 'help':
instructions = [['Instruction', 'Description'],
['-----------', '-----------'],
['setSpeeds', 'Specify the linear and angular velocity.'],
['setLimits', 'Specify the desired translation distance and rotation angle.'],
['toggleResetAfter', 'Reset the odom topic to zero after translating.'],
['publishReset', 'Manually reset the odom topic to zero.'],
['go', 'Make the robot translate until desired distance is reached.'],
['rotate', 'Make the robot rotate until the desired angle is reached.'],
['write', 'Write data list to csv file (called data.csv).'],
['stop', 'Stop the node.']]
for i in range(len(instructions)):
print('{:<20} {:<8}'.format(instructions[i][0], instructions[i][1])) | code used for testing/send_twist_msgs.py | import rospy
import numpy as np
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from std_msgs.msg import String
import tf_conversions
import tf2_ros
class CommandCenter(object):
def __init__(self):
self.pub_vel = rospy.Publisher("cmd_vel", Twist, queue_size = 10)
self.pub_reset = rospy.Publisher("command", String, queue_size = 1) #odometry_odometry_handler_collect_data.py subscribes to this topic
self.rate = rospy.Rate(20.0)
self.resetAfter = False
self.linear_x = 0.0
self.angular_z = 0.0
self.desired_distance = 0.0
self.desired_angle = 0.0
self.data = []
self.tfBuffer = tf2_ros.Buffer()
self.listener = tf2_ros.TransformListener(self.tfBuffer)
def publish_vel(self, twist_msg):
self.pub_vel.publish(twist_msg)
def publish_reset(self):
while not rospy.wait_for_message('odom', Odometry, timeout=1.0).pose.pose.position.x == 0.0:
self.pub_reset.publish("reset")
self.rate.sleep()
def write_to_csv(self):
np.savetxt('data.csv', self.data, fmt="%1.3f", delimiter=",", header='x,y', comments='') #the comments argument is needed because by default the header string will be preced by a # since the header, for numpy, is a comment
def createTwistMsg(self, x, z):
twist_msg = Twist()
twist_msg.linear.x = x
twist_msg.angular.z = z
return twist_msg
def translate(self):
available = False
while not available and not rospy.is_shutdown():
if self.tfBuffer.can_transform('odom', 'base_link', rospy.Time()):
available = True
start_transform = self.tfBuffer.lookup_transform('odom', 'base_link', rospy.Time())
start_xpos = start_transform.transform.translation.x
start_ypos = start_transform.transform.translation.y
done = False
while not done and not rospy.is_shutdown():
self.publish_vel(self.createTwistMsg(self.linear_x, 0.0))
self.rate.sleep()
try:
current_transform = self.tfBuffer.lookup_transform('odom', 'base_link', rospy.Time())
except (tf2_ros.LookupException, tf2_ros.ConnectivityException, tf2_ros.ExtrapolationException):
self.rate.sleep()
continue
current_xpos = current_transform.transform.translation.x
current_ypos = current_transform.transform.translation.y
if abs(current_xpos - start_xpos) >= self.desired_distance or abs(current_ypos - start_ypos) >= self.desired_distance:
self.publish_vel(self.createTwistMsg(0.0, 0.0))
if self.resetAfter:
msg = rospy.wait_for_message('odom', Odometry, timeout=1.0) # In theory we could also just use the current_transform
self.published_position.append([msg.pose.pose.position.x, msg.pose.pose.position.y])
self.publish_reset()
done = True
def rotate(self):
#checking if rotating clockwise or counter clockwise
if self.angular_z > 0:
clockwise = False
else:
clockwise = True
#checking if transform is available
available = False
while not available and not rospy.is_shutdown():
if self.tfBuffer.can_transform('odom', 'base_link', rospy.Time()):
available = True
#getting start transform
start_transform = self.tfBuffer.lookup_transform('odom', 'base_link', rospy.Time())
#getting the angle from the transform
start_angle = tf_conversions.transformations.euler_from_quaternion([start_transform.transform.rotation.x, start_transform.transform.rotation.y, start_transform.transform.rotation.z, start_transform.transform.rotation.w])[2]
#changing interval from [-pi, pi] to [0, 2*pi]
if not clockwise and start_angle < 0:
start_angle = start_angle + 2*np.pi
elif clockwise and start_angle > 0:
start_angle = 2*np.pi - start_angle
done = False
while not done and not rospy.is_shutdown():
#publishing twist message with specified angular velocity
self.publish_vel(self.createTwistMsg(0.0, self.angular_z))
self.rate.sleep()
#getting current transform
try:
current_transform = self.tfBuffer.lookup_transform('odom', 'base_link', rospy.Time())
except (tf2_ros.LookupException, tf2_ros.ConnectivityException, tf2_ros.ExtrapolationException):
self.rate.sleep()
continue
#getting the angle from the transform
current_angle = tf_conversions.transformations.euler_from_quaternion([current_transform.transform.rotation.x, current_transform.transform.rotation.y, current_transform.transform.rotation.z, current_transform.transform.rotation.w])[2]
#changing interval from [-pi, pi] to [0, 2*pi]
if not clockwise and current_angle < 0:
current_angle = current_angle + 2*np.pi
elif clockwise and current_angle > 0:
current_angle = current_angle - 2*np.pi
#calculating the angle between the transforms and converting it to degrees
relative_angle = abs(current_angle - start_angle) * 180 / np.pi
print('start_angle: {} current angle: {} angle_turned: {}'.format(start_angle*180/np.pi, current_angle*180/np.pi, relative_angle))
if relative_angle >= self.desired_angle:
self.publish_vel(self.createTwistMsg(0.0, 0.0))
done = True
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
if __name__ == "__main__":
rospy.init_node('send_twist_msgs_node', anonymous = False)
comc = CommandCenter()
print(bcolors.OKBLUE + 'Type "help" for all possible instructions.' + bcolors.ENDC)
speeds, limits = False, False
while not rospy.is_shutdown():
#checking if speeds and desired distance/angle have been set
if not speeds and not limits:
print(bcolors.FAIL + 'PLEASE SET SPEEDS AND DISTANCE/ANGLE WITH "setSpeeds" and "setLimits"' + bcolors.ENDC)
elif not speeds:
print(bcolors.FAIL + 'PLEASE SET SPEEDS with "setSpeeds"' + bcolors.ENDC)
elif not limits:
print(bcolors.FAIL + 'PLEASE SET DESIRED DISTANCE AND ANGLE WITH "setLimits"' + bcolors.ENDC)
#giving a warning if odom topic gets reset
if comc.resetAfter:
print(bcolors.WARNING + 'REMINDER: odom topic values will be reset to zero after a translation or rotation' + bcolors.ENDC)
#getting user input
user_input = raw_input('Give instruction: ')
#checking what the user input is and acting accordingly
if user_input == 'setSpeeds':
speed_vel = raw_input('Give linear velocity (in m/s) and rotational velocity (in rad/s) separated by a comma: ')
speed_vel = speed_vel.split(',')
try:
comc.linear_x = float(speed_vel[0])
comc.angular_z = float(speed_vel[1])
speeds = True
print(bcolors.OKGREEN + 'Set linear_x to: {} m/s and angular_z to: {} rad/s'.format(speed_vel[0], speed_vel[1]) + bcolors.ENDC)
except IndexError as e:
print(bcolors.FAIL + 'IndexError: ' + str(e) + bcolors.ENDC)
if user_input == 'setLimits':
dist_ang = raw_input('Give desired distance (in m) and desired angle (in degrees) seperated by a comma: ')
dist_ang = dist_ang.split(',')
try:
comc.desired_distance = float(dist_ang[0])
comc.desired_angle = float(dist_ang[1])
limits = True
print(bcolors.OKGREEN + 'Set desired_distance to: {} m and desired_angle to: {} degrees'.format(dist_ang[0], dist_ang[1]) + bcolors.ENDC)
except IndexError as e:
print(bcolors.FAIL + 'IndexError: ' + str(e) + bcolors.ENDC)
if user_input == 'toggleResetAfter':
if comc.resetAfter:
comc.resetAfter = False
else:
comc.resetAfter = True
print(bcolors.OKGREEN + 'resetAfter has been set to: {}'.format(comc.resetAfter) + bcolors.ENDC)
if user_input == 'publishReset':
comc.publish_reset()
if user_input == 'go':
comc.translate()
if user_input == 'rotate':
comc.rotate()
if user_input == 'write':
comc.write_to_csv()
if user_input == 'stop':
rospy.signal_shutdown("typed stop")
if user_input == 'help':
instructions = [['Instruction', 'Description'],
['-----------', '-----------'],
['setSpeeds', 'Specify the linear and angular velocity.'],
['setLimits', 'Specify the desired translation distance and rotation angle.'],
['toggleResetAfter', 'Reset the odom topic to zero after translating.'],
['publishReset', 'Manually reset the odom topic to zero.'],
['go', 'Make the robot translate until desired distance is reached.'],
['rotate', 'Make the robot rotate until the desired angle is reached.'],
['write', 'Write data list to csv file (called data.csv).'],
['stop', 'Stop the node.']]
for i in range(len(instructions)):
print('{:<20} {:<8}'.format(instructions[i][0], instructions[i][1])) | 0.413359 | 0.201794 |
from . import attach_common_event_handlers, chunk, parser_process_chunks
from .context import python_http_parser
def test_req():
"""
Test the stream/event based parser with a HTTP request that conforms to RFC7230
"""
errors = []
results = {
'req_method': None,
'req_uri': None,
'http_version': None,
'headers': {},
'raw_headers': []
}
msg = b"""\
GET /index.html HTTP/1.1
Host: example.com
User-Agent: Some-random-dude
X-Token: <PASSWORD>
"""
parser = python_http_parser.stream.HTTPParser()
attach_common_event_handlers(parser, results, errors, False)
parser.process(msg)
assert len(errors) == 0
assert parser.finished()
assert results['req_method'] == 'GET'
assert results['req_uri'] == '/index.html'
assert results['http_version'] == (1, 1)
assert len(results['raw_headers']) == 6
def test_req_extra_newlines():
"""
Test the event-based parser with a HTTP request that has preceding empyt lines.
"""
errors = []
results = {
'req_method': None,
'req_uri': None,
'http_version': None,
'headers': {},
'raw_headers': []
}
msg = b"""\
GET /more-newlines.html HTTP/1.1
Host: localhost:8080
User-Agent: Test runner/1.99999999999999999
Accept: text/*
"""
parser = python_http_parser.stream.HTTPParser()
attach_common_event_handlers(parser, results, errors, False)
parser.process(msg)
assert len(errors) == 0
assert parser.finished()
assert results['req_method'] == 'GET'
assert results['req_uri'] == '/more-newlines.html'
assert results['http_version'] == (1, 1)
assert len(results['raw_headers']) == 6
def test_chunked_req():
"""
Test the stream/event based parser with a HTTP request that doesn't arrive
at once.
"""
errors = []
results = {
'req_method': None,
'req_uri': None,
'http_version': None,
'headers': {},
'raw_headers': []
}
msg = b"""\
GET /index.html HTTP/1.1
Host: example.com
User-Agent: Some-random-dude
X-Token: <PASSWORD>
"""
parser = python_http_parser.stream.HTTPParser()
attach_common_event_handlers(parser, results, errors, False)
parser_process_chunks(parser, chunk(msg, 4))
assert len(errors) == 0
assert parser.finished()
assert results['req_method'] == 'GET'
assert results['req_uri'] == '/index.html'
assert results['http_version'] == (1, 1)
assert len(results['raw_headers']) == 6
def test_res():
"""
Test the stream/event based parser with a HTTP response that conform to RFC7230
"""
errors = []
results = {
'reason': None,
'status_code': None,
'req_uri': None,
'http_version': None,
'headers': {},
'raw_headers': []
}
msg = b"""\
HTTP/1.1 200 OK
Content-Length: 0
Date: Sat, 05 Jun 2021 22:56:51 GMT
X-CSRF-Token: <PASSWORD>
"""
parser = python_http_parser.stream.HTTPParser(is_response=True)
attach_common_event_handlers(parser, results, errors, True)
parser.process(msg)
assert len(errors) == 0
assert parser.finished()
assert results['http_version'] == (1, 1)
assert results['status_code'] == 200
assert results['reason'] == 'OK'
assert len(results['raw_headers']) == 6
def test_res_no_reason():
"""
Test the event-based parser with a HTTP response that does not have a reason phrase.
"""
errors = []
results = {
'reason': None,
'status_code': None,
'req_uri': None,
'http_version': None,
'headers': {},
'raw_headers': []
}
msg = b"""\
HTTP/1.1 200
Vary: Accept-Language
Cache-Control: max-age=900
Date: Sat, 05 Jun 2021 22:56:51 GMT
"""
parser = python_http_parser.stream.HTTPParser(is_response=True)
attach_common_event_handlers(parser, results, errors, True)
parser.process(msg)
assert len(errors) == 0
assert parser.finished()
assert results['http_version'] == (1, 1)
assert results['status_code'] == 200
assert results['reason'] == ''
assert len(results['raw_headers']) == 6
def test_chunked_res():
"""
Test the stream/event based parser with a HTTP response that doesn't arrive
at once.
"""
errors = []
results = {
'reason': None,
'status_code': None,
'req_uri': None,
'http_version': None,
'headers': {},
'raw_headers': []
}
msg = b''.join([
b'HTTP/1.1 200 OK\r\n',
b'Cache-Control: no-cache\r\n',
b"Content-Security-Policy: default-src 'none'\r\n",
b'Date: Sat, 05 Jun 2021 22:56:51 GMT\r\n\r\n'
])
parser = python_http_parser.stream.HTTPParser(is_response=True)
attach_common_event_handlers(parser, results, errors, True)
parser_process_chunks(parser, chunk(msg, 4))
assert len(errors) == 0
assert parser.finished()
assert results['http_version'] == (1, 1)
assert results['status_code'] == 200
assert results['reason'] == 'OK'
assert len(results['raw_headers']) == 6
def test_reset():
"""
Make sure the stream/event based parser could reset itself.
"""
errors = []
result = {
'reason': None,
'status_code': None,
'req_uri': None,
'http_version': None,
'headers': {},
'raw_headers': []
}
msg = b''.join([
b'HTTP/1.1 200 OK\r\n',
b'Cache-Control: no-cache\r\n',
b"Content-Security-Policy: default-src 'none'\r\n",
b'Date: Sat, 05 Jun 2021 22:56:51 GMT\r\n\r\n'
])
parser = python_http_parser.stream.HTTPParser(is_response=True)
attach_common_event_handlers(parser, result, errors, True)
parser.process(msg)
assert parser.finished()
assert len(errors) == 0
# Reset...
parser.reset()
assert not parser.finished()
assert len(errors) == 0
# Parse again :D
parser.process(msg)
assert parser.finished()
assert len(errors) == 0 | tests/test_stream.py |
from . import attach_common_event_handlers, chunk, parser_process_chunks
from .context import python_http_parser
def test_req():
"""
Test the stream/event based parser with a HTTP request that conforms to RFC7230
"""
errors = []
results = {
'req_method': None,
'req_uri': None,
'http_version': None,
'headers': {},
'raw_headers': []
}
msg = b"""\
GET /index.html HTTP/1.1
Host: example.com
User-Agent: Some-random-dude
X-Token: <PASSWORD>
"""
parser = python_http_parser.stream.HTTPParser()
attach_common_event_handlers(parser, results, errors, False)
parser.process(msg)
assert len(errors) == 0
assert parser.finished()
assert results['req_method'] == 'GET'
assert results['req_uri'] == '/index.html'
assert results['http_version'] == (1, 1)
assert len(results['raw_headers']) == 6
def test_req_extra_newlines():
"""
Test the event-based parser with a HTTP request that has preceding empyt lines.
"""
errors = []
results = {
'req_method': None,
'req_uri': None,
'http_version': None,
'headers': {},
'raw_headers': []
}
msg = b"""\
GET /more-newlines.html HTTP/1.1
Host: localhost:8080
User-Agent: Test runner/1.99999999999999999
Accept: text/*
"""
parser = python_http_parser.stream.HTTPParser()
attach_common_event_handlers(parser, results, errors, False)
parser.process(msg)
assert len(errors) == 0
assert parser.finished()
assert results['req_method'] == 'GET'
assert results['req_uri'] == '/more-newlines.html'
assert results['http_version'] == (1, 1)
assert len(results['raw_headers']) == 6
def test_chunked_req():
"""
Test the stream/event based parser with a HTTP request that doesn't arrive
at once.
"""
errors = []
results = {
'req_method': None,
'req_uri': None,
'http_version': None,
'headers': {},
'raw_headers': []
}
msg = b"""\
GET /index.html HTTP/1.1
Host: example.com
User-Agent: Some-random-dude
X-Token: <PASSWORD>
"""
parser = python_http_parser.stream.HTTPParser()
attach_common_event_handlers(parser, results, errors, False)
parser_process_chunks(parser, chunk(msg, 4))
assert len(errors) == 0
assert parser.finished()
assert results['req_method'] == 'GET'
assert results['req_uri'] == '/index.html'
assert results['http_version'] == (1, 1)
assert len(results['raw_headers']) == 6
def test_res():
"""
Test the stream/event based parser with a HTTP response that conform to RFC7230
"""
errors = []
results = {
'reason': None,
'status_code': None,
'req_uri': None,
'http_version': None,
'headers': {},
'raw_headers': []
}
msg = b"""\
HTTP/1.1 200 OK
Content-Length: 0
Date: Sat, 05 Jun 2021 22:56:51 GMT
X-CSRF-Token: <PASSWORD>
"""
parser = python_http_parser.stream.HTTPParser(is_response=True)
attach_common_event_handlers(parser, results, errors, True)
parser.process(msg)
assert len(errors) == 0
assert parser.finished()
assert results['http_version'] == (1, 1)
assert results['status_code'] == 200
assert results['reason'] == 'OK'
assert len(results['raw_headers']) == 6
def test_res_no_reason():
"""
Test the event-based parser with a HTTP response that does not have a reason phrase.
"""
errors = []
results = {
'reason': None,
'status_code': None,
'req_uri': None,
'http_version': None,
'headers': {},
'raw_headers': []
}
msg = b"""\
HTTP/1.1 200
Vary: Accept-Language
Cache-Control: max-age=900
Date: Sat, 05 Jun 2021 22:56:51 GMT
"""
parser = python_http_parser.stream.HTTPParser(is_response=True)
attach_common_event_handlers(parser, results, errors, True)
parser.process(msg)
assert len(errors) == 0
assert parser.finished()
assert results['http_version'] == (1, 1)
assert results['status_code'] == 200
assert results['reason'] == ''
assert len(results['raw_headers']) == 6
def test_chunked_res():
"""
Test the stream/event based parser with a HTTP response that doesn't arrive
at once.
"""
errors = []
results = {
'reason': None,
'status_code': None,
'req_uri': None,
'http_version': None,
'headers': {},
'raw_headers': []
}
msg = b''.join([
b'HTTP/1.1 200 OK\r\n',
b'Cache-Control: no-cache\r\n',
b"Content-Security-Policy: default-src 'none'\r\n",
b'Date: Sat, 05 Jun 2021 22:56:51 GMT\r\n\r\n'
])
parser = python_http_parser.stream.HTTPParser(is_response=True)
attach_common_event_handlers(parser, results, errors, True)
parser_process_chunks(parser, chunk(msg, 4))
assert len(errors) == 0
assert parser.finished()
assert results['http_version'] == (1, 1)
assert results['status_code'] == 200
assert results['reason'] == 'OK'
assert len(results['raw_headers']) == 6
def test_reset():
"""
Make sure the stream/event based parser could reset itself.
"""
errors = []
result = {
'reason': None,
'status_code': None,
'req_uri': None,
'http_version': None,
'headers': {},
'raw_headers': []
}
msg = b''.join([
b'HTTP/1.1 200 OK\r\n',
b'Cache-Control: no-cache\r\n',
b"Content-Security-Policy: default-src 'none'\r\n",
b'Date: Sat, 05 Jun 2021 22:56:51 GMT\r\n\r\n'
])
parser = python_http_parser.stream.HTTPParser(is_response=True)
attach_common_event_handlers(parser, result, errors, True)
parser.process(msg)
assert parser.finished()
assert len(errors) == 0
# Reset...
parser.reset()
assert not parser.finished()
assert len(errors) == 0
# Parse again :D
parser.process(msg)
assert parser.finished()
assert len(errors) == 0 | 0.646349 | 0.265749 |
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk
import conjuntos
class Janela(Gtk.Window):
def __init__(self):
#Janela Principal
Gtk.Window.__init__(self, title="Álgebra de Conjuntos")
Gtk.Window.set_size_request(self,500,400)
Gtk.Window.set_resizable(self,False)
Gtk.Window.modify_bg(self,Gtk.StateType.NORMAL,Gdk.color_parse("#cccccc"))
#Grid_total
self.grid_total = Gtk.Grid()
self.add(self.grid_total)
self.grid1 = Gtk.Grid()
self.grid1 = Gtk.Grid(column_homogeneous=False,column_spacing=10,row_spacing=10)
#Texto e box de escolha para a Operação
self.combo = Gtk.ComboBoxText()
self.label_combo = Gtk.Label(label="Operação: ")
self.label_combo.set_halign(Gtk.Align.END)
self.grid1.attach(self.label_combo,1,2,1,1)
self.combo.insert(0,"0", "União (A U B)")
self.combo.insert(1,"1", "Interseção (A ∩ B)")
self.combo.insert(2,"2", "Diferença (A - B)")
self.combo.insert(3,"3", "Diferença Simétrica (A △ B)")
self.combo.insert(4,"4", "Complementar (Ac)")
self.combo.set_halign(Gtk.Align.START)
self.grid1.attach(self.combo, 2,2,1,1)
#Texto e Campo de entrada do Conjunto A
self.label_conjuntoA = Gtk.Label(label=" Conjunto A: ")
self.label_conjuntoA.set_halign(Gtk.Align.END)
self.grid1.attach(self.label_conjuntoA,1,4,1,1)
self.entry_conjuntoA = Gtk.Entry()
self.entry_conjuntoA.set_max_length(100)
self.entry_conjuntoA.set_width_chars(50)
self.entry_conjuntoA.set_halign(Gtk.Align.FILL)
self.grid1.attach(self.entry_conjuntoA, 2,4,1,1)
self.entry_conjuntoA.set_text("1,2,3")
#Texto e Campo de entrada do conjunto B
self.label_conjuntoB = Gtk.Label(label=" Conjunto B: ")
self.label_conjuntoB.set_halign(Gtk.Align.END)
self.grid1.attach(self.label_conjuntoB,1,6,1,1)
self.entry_conjuntoB = Gtk.Entry()
self.entry_conjuntoB.set_max_length(100)
self.entry_conjuntoB.set_width_chars(50)
self.entry_conjuntoB.set_halign(Gtk.Align.FILL)
self.grid1.attach(self.entry_conjuntoB, 2,6,1,1)
self.entry_conjuntoB.set_text("4,5,6")
#Botão de Resultado
self.button = Gtk.Button(label="Ver Solução")
self.button.set_halign(Gtk.Align.START)
self.grid1.attach(self.button,2,12,2,2)
self.button.connect("clicked", self.button_clicked)
#Texto de Resultado / Conjunto Solução
self.label_solucao = Gtk.Label(label=" ")
self.label_solucao.set_halign(Gtk.Align.START)
self.grid1.attach(self.label_solucao,2,18,1,1)
#Espaçamento das grids
self.grid1.set_row_spacing(30)
self.box3 = Gtk.Box()
#Colocando a Grid1 e box3 na grid principal
self.grid_total.set_row_spacing(20)
self.grid_total.attach(self.grid1, 0,3,2,1)
self.grid_total.attach(self.box3, 0,9,1,1)
def button_clicked(self, widget):
operacao = self.combo.get_active_text()
conjunto_a = self.entry_conjuntoA.get_text()
conjunto_b = self.entry_conjuntoB.get_text()
conjunto_a = conjunto_a.split(',')
conjunto_b = conjunto_b.split(',')
resultado = []
if(operacao == "União (A U B)"):
resultado = conjuntos.uniao(conjunto_a, conjunto_b)
elif(operacao == "Interseção (A ∩ B)"):
resultado = conjuntos.intersecao(conjunto_a, conjunto_b)
elif(operacao == "Diferença (A - B)"):
resultado = conjuntos.diferenca(conjunto_a, conjunto_b)
elif(operacao == "Diferença Simétrica (A △ B)"):
resultado = conjuntos.difSimetrica(conjunto_a, conjunto_b)
elif(operacao == "Complementar (Ac)"):
resultado = conjuntos.diferenca(conjunto_b, conjunto_a)
try:
resultado = [float(i) for i in resultado]
resultado = conjuntos.ordenaVetor(resultado)
resultado = ", ".join(str(x) for x in resultado)
resultado = "[" + resultado + "]"
self.label_solucao.set_text(resultado)
except:
self.label_solucao.set_text("Por favor, insira elementos válidos nos dois conjuntos!\n\nEx: 1,2,3,4,5")
if(operacao == None):
self.label_solucao.set_text("Escolha uma operação!")
elif(resultado == "[]"):
self.label_solucao.set_text("[ ] ou ø")
#Inicialização da aplicação
win = Janela()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main() | gui_conjuntos.py | import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk
import conjuntos
class Janela(Gtk.Window):
def __init__(self):
#Janela Principal
Gtk.Window.__init__(self, title="Álgebra de Conjuntos")
Gtk.Window.set_size_request(self,500,400)
Gtk.Window.set_resizable(self,False)
Gtk.Window.modify_bg(self,Gtk.StateType.NORMAL,Gdk.color_parse("#cccccc"))
#Grid_total
self.grid_total = Gtk.Grid()
self.add(self.grid_total)
self.grid1 = Gtk.Grid()
self.grid1 = Gtk.Grid(column_homogeneous=False,column_spacing=10,row_spacing=10)
#Texto e box de escolha para a Operação
self.combo = Gtk.ComboBoxText()
self.label_combo = Gtk.Label(label="Operação: ")
self.label_combo.set_halign(Gtk.Align.END)
self.grid1.attach(self.label_combo,1,2,1,1)
self.combo.insert(0,"0", "União (A U B)")
self.combo.insert(1,"1", "Interseção (A ∩ B)")
self.combo.insert(2,"2", "Diferença (A - B)")
self.combo.insert(3,"3", "Diferença Simétrica (A △ B)")
self.combo.insert(4,"4", "Complementar (Ac)")
self.combo.set_halign(Gtk.Align.START)
self.grid1.attach(self.combo, 2,2,1,1)
#Texto e Campo de entrada do Conjunto A
self.label_conjuntoA = Gtk.Label(label=" Conjunto A: ")
self.label_conjuntoA.set_halign(Gtk.Align.END)
self.grid1.attach(self.label_conjuntoA,1,4,1,1)
self.entry_conjuntoA = Gtk.Entry()
self.entry_conjuntoA.set_max_length(100)
self.entry_conjuntoA.set_width_chars(50)
self.entry_conjuntoA.set_halign(Gtk.Align.FILL)
self.grid1.attach(self.entry_conjuntoA, 2,4,1,1)
self.entry_conjuntoA.set_text("1,2,3")
#Texto e Campo de entrada do conjunto B
self.label_conjuntoB = Gtk.Label(label=" Conjunto B: ")
self.label_conjuntoB.set_halign(Gtk.Align.END)
self.grid1.attach(self.label_conjuntoB,1,6,1,1)
self.entry_conjuntoB = Gtk.Entry()
self.entry_conjuntoB.set_max_length(100)
self.entry_conjuntoB.set_width_chars(50)
self.entry_conjuntoB.set_halign(Gtk.Align.FILL)
self.grid1.attach(self.entry_conjuntoB, 2,6,1,1)
self.entry_conjuntoB.set_text("4,5,6")
#Botão de Resultado
self.button = Gtk.Button(label="Ver Solução")
self.button.set_halign(Gtk.Align.START)
self.grid1.attach(self.button,2,12,2,2)
self.button.connect("clicked", self.button_clicked)
#Texto de Resultado / Conjunto Solução
self.label_solucao = Gtk.Label(label=" ")
self.label_solucao.set_halign(Gtk.Align.START)
self.grid1.attach(self.label_solucao,2,18,1,1)
#Espaçamento das grids
self.grid1.set_row_spacing(30)
self.box3 = Gtk.Box()
#Colocando a Grid1 e box3 na grid principal
self.grid_total.set_row_spacing(20)
self.grid_total.attach(self.grid1, 0,3,2,1)
self.grid_total.attach(self.box3, 0,9,1,1)
def button_clicked(self, widget):
operacao = self.combo.get_active_text()
conjunto_a = self.entry_conjuntoA.get_text()
conjunto_b = self.entry_conjuntoB.get_text()
conjunto_a = conjunto_a.split(',')
conjunto_b = conjunto_b.split(',')
resultado = []
if(operacao == "União (A U B)"):
resultado = conjuntos.uniao(conjunto_a, conjunto_b)
elif(operacao == "Interseção (A ∩ B)"):
resultado = conjuntos.intersecao(conjunto_a, conjunto_b)
elif(operacao == "Diferença (A - B)"):
resultado = conjuntos.diferenca(conjunto_a, conjunto_b)
elif(operacao == "Diferença Simétrica (A △ B)"):
resultado = conjuntos.difSimetrica(conjunto_a, conjunto_b)
elif(operacao == "Complementar (Ac)"):
resultado = conjuntos.diferenca(conjunto_b, conjunto_a)
try:
resultado = [float(i) for i in resultado]
resultado = conjuntos.ordenaVetor(resultado)
resultado = ", ".join(str(x) for x in resultado)
resultado = "[" + resultado + "]"
self.label_solucao.set_text(resultado)
except:
self.label_solucao.set_text("Por favor, insira elementos válidos nos dois conjuntos!\n\nEx: 1,2,3,4,5")
if(operacao == None):
self.label_solucao.set_text("Escolha uma operação!")
elif(resultado == "[]"):
self.label_solucao.set_text("[ ] ou ø")
#Inicialização da aplicação
win = Janela()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main() | 0.29798 | 0.255119 |
import asyncio
from datetime import datetime, timedelta
from typing import Union
from pyrogram import Client
from pyrogram.errors import (ChatAdminRequired,
UserAlreadyParticipant,
UserNotParticipant)
from pyrogram.types import InlineKeyboardMarkup
from pytgcalls import PyTgCalls, StreamType
from pytgcalls.exceptions import (AlreadyJoinedError,
NoActiveGroupCall,
TelegramServerError)
from pytgcalls.types import (JoinedGroupCallParticipant,
LeftGroupCallParticipant, Update)
from pytgcalls.types.input_stream import AudioPiped, AudioVideoPiped
from pytgcalls.types.stream import StreamAudioEnded
import config
from strings import get_string
from YukkiMusic import LOGGER, YouTube, app
from YukkiMusic.misc import db
from YukkiMusic.utils.database import (add_active_chat,
add_active_video_chat,
get_assistant,
get_audio_bitrate, get_lang,
get_loop, get_video_bitrate,
group_assistant, is_autoend,
music_on, mute_off,
remove_active_chat,
remove_active_video_chat,
set_loop)
from YukkiMusic.utils.exceptions import AssistantErr
from YukkiMusic.utils.inline.play import (stream_markup,
telegram_markup)
from YukkiMusic.utils.stream.autoclear import auto_clean
from YukkiMusic.utils.thumbnails import gen_thumb
autoend = {}
counter = {}
AUTO_END_TIME = 3
async def _clear_(chat_id):
db[chat_id] = []
await remove_active_video_chat(chat_id)
await remove_active_chat(chat_id)
class Call(PyTgCalls):
def __init__(self):
self.userbot1 = Client(
api_id=config.API_ID,
api_hash=config.API_HASH,
session_name=str(config.STRING1),
)
self.one = PyTgCalls(
self.userbot1,
cache_duration=100,
)
self.userbot2 = Client(
api_id=config.API_ID,
api_hash=config.API_HASH,
session_name=str(config.STRING2),
)
self.two = PyTgCalls(
self.userbot2,
cache_duration=100,
)
self.userbot3 = Client(
api_id=config.API_ID,
api_hash=config.API_HASH,
session_name=str(config.STRING3),
)
self.three = PyTgCalls(
self.userbot3,
cache_duration=100,
)
self.userbot4 = Client(
api_id=config.API_ID,
api_hash=config.API_HASH,
session_name=str(config.STRING4),
)
self.four = PyTgCalls(
self.userbot4,
cache_duration=100,
)
self.userbot5 = Client(
api_id=config.API_ID,
api_hash=config.API_HASH,
session_name=str(config.STRING5),
)
self.five = PyTgCalls(
self.userbot5,
cache_duration=100,
)
async def pause_stream(self, chat_id: int):
assistant = await group_assistant(self, chat_id)
await assistant.pause_stream(chat_id)
async def resume_stream(self, chat_id: int):
assistant = await group_assistant(self, chat_id)
await assistant.resume_stream(chat_id)
async def mute_stream(self, chat_id: int):
assistant = await group_assistant(self, chat_id)
await assistant.mute_stream(chat_id)
async def unmute_stream(self, chat_id: int):
assistant = await group_assistant(self, chat_id)
await assistant.unmute_stream(chat_id)
async def stop_stream(self, chat_id: int):
assistant = await group_assistant(self, chat_id)
try:
await _clear_(chat_id)
await assistant.leave_group_call(chat_id)
except:
pass
async def force_stop_stream(self, chat_id: int):
assistant = await group_assistant(self, chat_id)
try:
check = db.get(chat_id)
check.pop(0)
except:
pass
await remove_active_video_chat(chat_id)
await remove_active_chat(chat_id)
try:
await assistant.leave_group_call(chat_id)
except:
pass
async def skip_stream(
self, chat_id: int, link: str, video: Union[bool, str] = None
):
assistant = await group_assistant(self, chat_id)
audio_stream_quality = await get_audio_bitrate(chat_id)
video_stream_quality = await get_video_bitrate(chat_id)
stream = (
AudioVideoPiped(
link,
audio_parameters=audio_stream_quality,
video_parameters=video_stream_quality,
)
if video
else AudioPiped(
link, audio_parameters=audio_stream_quality
)
)
await assistant.change_stream(
chat_id,
stream,
)
async def seek_stream(
self, chat_id, file_path, to_seek, duration, mode
):
assistant = await group_assistant(self, chat_id)
audio_stream_quality = await get_audio_bitrate(chat_id)
video_stream_quality = await get_video_bitrate(chat_id)
stream = (
AudioVideoPiped(
file_path,
audio_parameters=audio_stream_quality,
video_parameters=video_stream_quality,
additional_ffmpeg_parameters=f"-ss {to_seek} -to {duration}",
)
if mode == "video"
else AudioPiped(
file_path,
audio_parameters=audio_stream_quality,
additional_ffmpeg_parameters=f"-ss {to_seek} -to {duration}",
)
)
await assistant.change_stream(chat_id, stream)
async def stream_call(self, link):
assistant = await group_assistant(self, config.LOG_GROUP_ID)
await assistant.join_group_call(
config.LOG_GROUP_ID,
AudioVideoPiped(link),
stream_type=StreamType().pulse_stream,
)
await asyncio.sleep(0.5)
await assistant.leave_group_call(config.LOG_GROUP_ID)
async def join_assistant(self, original_chat_id, chat_id):
language = await get_lang(original_chat_id)
_ = get_string(language)
userbot = await get_assistant(chat_id)
try:
try:
get = await app.get_chat_member(chat_id, userbot.id)
except ChatAdminRequired:
raise AssistantErr(_["call_1"])
if get.status == "banned" or get.status == "kicked":
raise AssistantErr(
_["call_2"].format(userbot.username, userbot.id)
)
except UserNotParticipant:
chat = await app.get_chat(chat_id)
if chat.username:
try:
await userbot.join_chat(chat.username)
except UserAlreadyParticipant:
pass
except Exception as e:
raise AssistantErr(_["call_3"].format(e))
else:
try:
try:
try:
invitelink = chat.invite_link
if invitelink is None:
invitelink = (
await app.export_chat_invite_link(
chat_id
)
)
except:
invitelink = (
await app.export_chat_invite_link(
chat_id
)
)
except ChatAdminRequired:
raise AssistantErr(_["call_4"])
except Exception as e:
raise AssistantErr(e)
m = await app.send_message(
original_chat_id, _["call_5"]
)
if invitelink.startswith("https://t.me/+"):
invitelink = invitelink.replace(
"https://t.me/+", "https://t.me/joinchat/"
)
await asyncio.sleep(3)
await userbot.join_chat(invitelink)
await asyncio.sleep(4)
await m.edit(_["call_6"].format(userbot.name))
except UserAlreadyParticipant:
pass
except Exception as e:
raise AssistantErr(_["call_3"].format(e))
async def join_call(
self,
chat_id: int,
original_chat_id: int,
link,
video: Union[bool, str] = None,
):
assistant = await group_assistant(self, chat_id)
audio_stream_quality = await get_audio_bitrate(chat_id)
video_stream_quality = await get_video_bitrate(chat_id)
stream = (
AudioVideoPiped(
link,
audio_parameters=audio_stream_quality,
video_parameters=video_stream_quality,
)
if video
else AudioPiped(
link, audio_parameters=audio_stream_quality
)
)
try:
await assistant.join_group_call(
chat_id,
stream,
stream_type=StreamType().pulse_stream,
)
except NoActiveGroupCall:
try:
await self.join_assistant(original_chat_id, chat_id)
except Exception as e:
raise e
try:
await assistant.join_group_call(
chat_id,
stream,
stream_type=StreamType().pulse_stream,
)
except Exception as e:
raise AssistantErr(
"**No Active Voice Chat Found**\n\nPlease make sure group's voice chat is enabled. If already enabled, please end it and start fresh voice chat again and if the problem continues, try /restart"
)
except AlreadyJoinedError:
raise AssistantErr(
"**Assistant Already in Voice Chat**\n\nSystems have detected that assistant is already there in the voice chat, this issue generally comes when you play 2 queries together.\n\nIf assistant is not present in voice chat, please end voice chat and start fresh voice chat again and if the problem continues, try /restart"
)
except TelegramServerError:
raise AssistantErr(
"**Telegram Server Error**\n\nTelegram is having some internal server problems, Please try playing again.\n\n If this problem keeps coming everytime, please end your voice chat and start fresh voice chat again."
)
await add_active_chat(chat_id)
await mute_off(chat_id)
await music_on(chat_id)
if video:
await add_active_video_chat(chat_id)
if await is_autoend():
counter[chat_id] = {}
users = len(await assistant.get_participants(chat_id))
if users == 1:
autoend[chat_id] = datetime.now() + timedelta(
minutes=AUTO_END_TIME
)
async def change_stream(self, client, chat_id):
check = db.get(chat_id)
popped = None
loop = await get_loop(chat_id)
try:
if loop == 0:
popped = check.pop(0)
else:
loop = loop - 1
await set_loop(chat_id, loop)
if popped:
if config.AUTO_DOWNLOADS_CLEAR == str(True):
await auto_clean(popped)
if not check:
await _clear_(chat_id)
return await client.leave_group_call(chat_id)
except:
try:
await _clear_(chat_id)
return await client.leave_group_call(chat_id)
except:
return
else:
queued = check[0]["file"]
language = await get_lang(chat_id)
_ = get_string(language)
title = (check[0]["title"]).title()
user = check[0]["by"]
original_chat_id = check[0]["chat_id"]
streamtype = check[0]["streamtype"]
audio_stream_quality = await get_audio_bitrate(chat_id)
video_stream_quality = await get_video_bitrate(chat_id)
videoid = check[0]["vidid"]
check[0]["played"] = 0
if "live_" in queued:
n, link = await YouTube.video(videoid, True)
if n == 0:
return await app.send_message(
original_chat_id,
text=_["call_9"],
)
stream = (
AudioVideoPiped(
link,
audio_parameters=audio_stream_quality,
video_parameters=video_stream_quality,
)
if str(streamtype) == "video"
else AudioPiped(
link, audio_parameters=audio_stream_quality
)
)
try:
await client.change_stream(chat_id, stream)
except Exception:
return await app.send_message(
original_chat_id,
text=_["call_9"],
)
img = await gen_thumb(videoid)
button = telegram_markup(_, chat_id)
run = await app.send_photo(
original_chat_id,
photo=img,
caption=_["stream_1"].format(
user,
f"https://t.me/{app.username}?start=info_{videoid}",
),
reply_markup=InlineKeyboardMarkup(button),
)
db[chat_id][0]["mystic"] = run
db[chat_id][0]["markup"] = "tg"
elif "vid_" in queued:
mystic = await app.send_message(
original_chat_id, _["call_10"]
)
try:
file_path, direct = await YouTube.download(
videoid,
mystic,
videoid=True,
video=True
if str(streamtype) == "video"
else False,
)
except:
return await mystic.edit_text(
_["call_9"], disable_web_page_preview=True
)
stream = (
AudioVideoPiped(
file_path,
audio_parameters=audio_stream_quality,
video_parameters=video_stream_quality,
)
if str(streamtype) == "video"
else AudioPiped(
file_path,
audio_parameters=audio_stream_quality,
)
)
try:
await client.change_stream(chat_id, stream)
except Exception:
return await app.send_message(
original_chat_id,
text=_["call_9"],
)
img = await gen_thumb(videoid)
button = stream_markup(_, videoid, chat_id)
await mystic.delete()
run = await app.send_photo(
original_chat_id,
photo=img,
caption=_["stream_1"].format(
user,
f"https://t.me/{app.username}?start=info_{videoid}",
),
reply_markup=InlineKeyboardMarkup(button),
)
db[chat_id][0]["mystic"] = run
db[chat_id][0]["markup"] = "stream"
elif "index_" in queued:
stream = (
AudioVideoPiped(
videoid,
audio_parameters=audio_stream_quality,
video_parameters=video_stream_quality,
)
if str(streamtype) == "video"
else AudioPiped(
videoid, audio_parameters=audio_stream_quality
)
)
try:
await client.change_stream(chat_id, stream)
except Exception:
return await app.send_message(
original_chat_id,
text=_["call_9"],
)
button = telegram_markup(_, chat_id)
run = await app.send_photo(
original_chat_id,
photo=config.STREAM_IMG_URL,
caption=_["stream_2"].format(user),
reply_markup=InlineKeyboardMarkup(button),
)
db[chat_id][0]["mystic"] = run
db[chat_id][0]["markup"] = "tg"
else:
stream = (
AudioVideoPiped(
queued,
audio_parameters=audio_stream_quality,
video_parameters=video_stream_quality,
)
if str(streamtype) == "video"
else AudioPiped(
queued, audio_parameters=audio_stream_quality
)
)
try:
await client.change_stream(chat_id, stream)
except Exception:
return await app.send_message(
original_chat_id,
text=_["call_9"],
)
if videoid == "telegram":
button = telegram_markup(_, chat_id)
run = await app.send_photo(
original_chat_id,
photo=config.TELEGRAM_AUDIO_URL
if str(streamtype) == "audio"
else config.TELEGRAM_VIDEO_URL,
caption=_["stream_3"].format(
title, check[0]["dur"], user
),
reply_markup=InlineKeyboardMarkup(button),
)
db[chat_id][0]["mystic"] = run
db[chat_id][0]["markup"] = "tg"
elif videoid == "soundcloud":
button = telegram_markup(_, chat_id)
run = await app.send_photo(
original_chat_id,
photo=config.SOUNCLOUD_IMG_URL,
caption=_["stream_3"].format(
title, check[0]["dur"], user
),
reply_markup=InlineKeyboardMarkup(button),
)
db[chat_id][0]["mystic"] = run
db[chat_id][0]["markup"] = "tg"
else:
img = await gen_thumb(videoid)
button = stream_markup(_, videoid, chat_id)
run = await app.send_photo(
original_chat_id,
photo=img,
caption=_["stream_1"].format(
user,
f"https://t.me/{app.username}?start=info_{videoid}",
),
reply_markup=InlineKeyboardMarkup(button),
)
db[chat_id][0]["mystic"] = run
db[chat_id][0]["markup"] = "stream"
async def ping(self):
pings = []
if config.STRING1:
pings.append(await self.one.ping)
if config.STRING2:
pings.append(await self.two.ping)
if config.STRING3:
pings.append(await self.three.ping)
if config.STRING4:
pings.append(await self.four.ping)
if config.STRING5:
pings.append(await self.five.ping)
return str(round(sum(pings) / len(pings), 3))
async def start(self):
LOGGER(__name__).info("Starting PyTgCalls Client\n")
if config.STRING1:
await self.one.start()
if config.STRING2:
await self.two.start()
if config.STRING3:
await self.three.start()
if config.STRING4:
await self.four.start()
if config.STRING5:
await self.five.start()
async def decorators(self):
@self.one.on_kicked()
@self.two.on_kicked()
@self.three.on_kicked()
@self.four.on_kicked()
@self.five.on_kicked()
@self.one.on_closed_voice_chat()
@self.two.on_closed_voice_chat()
@self.three.on_closed_voice_chat()
@self.four.on_closed_voice_chat()
@self.five.on_closed_voice_chat()
@self.one.on_left()
@self.two.on_left()
@self.three.on_left()
@self.four.on_left()
@self.five.on_left()
async def stream_services_handler(_, chat_id: int):
await self.stop_stream(chat_id)
@self.one.on_stream_end()
@self.two.on_stream_end()
@self.three.on_stream_end()
@self.four.on_stream_end()
@self.five.on_stream_end()
async def stream_end_handler1(client, update: Update):
if not isinstance(update, StreamAudioEnded):
return
await self.change_stream(client, update.chat_id)
@self.one.on_participants_change()
@self.two.on_participants_change()
@self.three.on_participants_change()
@self.four.on_participants_change()
@self.five.on_participants_change()
async def participants_change_handler(client, update: Update):
if not isinstance(
update, JoinedGroupCallParticipant
) and not isinstance(update, LeftGroupCallParticipant):
return
chat_id = update.chat_id
users = counter.get(chat_id)
if not users:
try:
got = len(await client.get_participants(chat_id))
except:
return
counter[chat_id] = got
if got == 1:
autoend[chat_id] = datetime.now() + timedelta(
minutes=AUTO_END_TIME
)
return
autoend[chat_id] = {}
else:
final = (
users + 1
if isinstance(update, JoinedGroupCallParticipant)
else users - 1
)
counter[chat_id] = final
if final == 1:
autoend[chat_id] = datetime.now() + timedelta(
minutes=AUTO_END_TIME
)
return
autoend[chat_id] = {}
Yukki = Call() | YukkiMusic/core/call.py |
import asyncio
from datetime import datetime, timedelta
from typing import Union
from pyrogram import Client
from pyrogram.errors import (ChatAdminRequired,
UserAlreadyParticipant,
UserNotParticipant)
from pyrogram.types import InlineKeyboardMarkup
from pytgcalls import PyTgCalls, StreamType
from pytgcalls.exceptions import (AlreadyJoinedError,
NoActiveGroupCall,
TelegramServerError)
from pytgcalls.types import (JoinedGroupCallParticipant,
LeftGroupCallParticipant, Update)
from pytgcalls.types.input_stream import AudioPiped, AudioVideoPiped
from pytgcalls.types.stream import StreamAudioEnded
import config
from strings import get_string
from YukkiMusic import LOGGER, YouTube, app
from YukkiMusic.misc import db
from YukkiMusic.utils.database import (add_active_chat,
add_active_video_chat,
get_assistant,
get_audio_bitrate, get_lang,
get_loop, get_video_bitrate,
group_assistant, is_autoend,
music_on, mute_off,
remove_active_chat,
remove_active_video_chat,
set_loop)
from YukkiMusic.utils.exceptions import AssistantErr
from YukkiMusic.utils.inline.play import (stream_markup,
telegram_markup)
from YukkiMusic.utils.stream.autoclear import auto_clean
from YukkiMusic.utils.thumbnails import gen_thumb
autoend = {}
counter = {}
AUTO_END_TIME = 3
async def _clear_(chat_id):
db[chat_id] = []
await remove_active_video_chat(chat_id)
await remove_active_chat(chat_id)
class Call(PyTgCalls):
def __init__(self):
self.userbot1 = Client(
api_id=config.API_ID,
api_hash=config.API_HASH,
session_name=str(config.STRING1),
)
self.one = PyTgCalls(
self.userbot1,
cache_duration=100,
)
self.userbot2 = Client(
api_id=config.API_ID,
api_hash=config.API_HASH,
session_name=str(config.STRING2),
)
self.two = PyTgCalls(
self.userbot2,
cache_duration=100,
)
self.userbot3 = Client(
api_id=config.API_ID,
api_hash=config.API_HASH,
session_name=str(config.STRING3),
)
self.three = PyTgCalls(
self.userbot3,
cache_duration=100,
)
self.userbot4 = Client(
api_id=config.API_ID,
api_hash=config.API_HASH,
session_name=str(config.STRING4),
)
self.four = PyTgCalls(
self.userbot4,
cache_duration=100,
)
self.userbot5 = Client(
api_id=config.API_ID,
api_hash=config.API_HASH,
session_name=str(config.STRING5),
)
self.five = PyTgCalls(
self.userbot5,
cache_duration=100,
)
async def pause_stream(self, chat_id: int):
assistant = await group_assistant(self, chat_id)
await assistant.pause_stream(chat_id)
async def resume_stream(self, chat_id: int):
assistant = await group_assistant(self, chat_id)
await assistant.resume_stream(chat_id)
async def mute_stream(self, chat_id: int):
assistant = await group_assistant(self, chat_id)
await assistant.mute_stream(chat_id)
async def unmute_stream(self, chat_id: int):
assistant = await group_assistant(self, chat_id)
await assistant.unmute_stream(chat_id)
async def stop_stream(self, chat_id: int):
assistant = await group_assistant(self, chat_id)
try:
await _clear_(chat_id)
await assistant.leave_group_call(chat_id)
except:
pass
async def force_stop_stream(self, chat_id: int):
assistant = await group_assistant(self, chat_id)
try:
check = db.get(chat_id)
check.pop(0)
except:
pass
await remove_active_video_chat(chat_id)
await remove_active_chat(chat_id)
try:
await assistant.leave_group_call(chat_id)
except:
pass
async def skip_stream(
self, chat_id: int, link: str, video: Union[bool, str] = None
):
assistant = await group_assistant(self, chat_id)
audio_stream_quality = await get_audio_bitrate(chat_id)
video_stream_quality = await get_video_bitrate(chat_id)
stream = (
AudioVideoPiped(
link,
audio_parameters=audio_stream_quality,
video_parameters=video_stream_quality,
)
if video
else AudioPiped(
link, audio_parameters=audio_stream_quality
)
)
await assistant.change_stream(
chat_id,
stream,
)
async def seek_stream(
self, chat_id, file_path, to_seek, duration, mode
):
assistant = await group_assistant(self, chat_id)
audio_stream_quality = await get_audio_bitrate(chat_id)
video_stream_quality = await get_video_bitrate(chat_id)
stream = (
AudioVideoPiped(
file_path,
audio_parameters=audio_stream_quality,
video_parameters=video_stream_quality,
additional_ffmpeg_parameters=f"-ss {to_seek} -to {duration}",
)
if mode == "video"
else AudioPiped(
file_path,
audio_parameters=audio_stream_quality,
additional_ffmpeg_parameters=f"-ss {to_seek} -to {duration}",
)
)
await assistant.change_stream(chat_id, stream)
async def stream_call(self, link):
assistant = await group_assistant(self, config.LOG_GROUP_ID)
await assistant.join_group_call(
config.LOG_GROUP_ID,
AudioVideoPiped(link),
stream_type=StreamType().pulse_stream,
)
await asyncio.sleep(0.5)
await assistant.leave_group_call(config.LOG_GROUP_ID)
async def join_assistant(self, original_chat_id, chat_id):
language = await get_lang(original_chat_id)
_ = get_string(language)
userbot = await get_assistant(chat_id)
try:
try:
get = await app.get_chat_member(chat_id, userbot.id)
except ChatAdminRequired:
raise AssistantErr(_["call_1"])
if get.status == "banned" or get.status == "kicked":
raise AssistantErr(
_["call_2"].format(userbot.username, userbot.id)
)
except UserNotParticipant:
chat = await app.get_chat(chat_id)
if chat.username:
try:
await userbot.join_chat(chat.username)
except UserAlreadyParticipant:
pass
except Exception as e:
raise AssistantErr(_["call_3"].format(e))
else:
try:
try:
try:
invitelink = chat.invite_link
if invitelink is None:
invitelink = (
await app.export_chat_invite_link(
chat_id
)
)
except:
invitelink = (
await app.export_chat_invite_link(
chat_id
)
)
except ChatAdminRequired:
raise AssistantErr(_["call_4"])
except Exception as e:
raise AssistantErr(e)
m = await app.send_message(
original_chat_id, _["call_5"]
)
if invitelink.startswith("https://t.me/+"):
invitelink = invitelink.replace(
"https://t.me/+", "https://t.me/joinchat/"
)
await asyncio.sleep(3)
await userbot.join_chat(invitelink)
await asyncio.sleep(4)
await m.edit(_["call_6"].format(userbot.name))
except UserAlreadyParticipant:
pass
except Exception as e:
raise AssistantErr(_["call_3"].format(e))
async def join_call(
self,
chat_id: int,
original_chat_id: int,
link,
video: Union[bool, str] = None,
):
assistant = await group_assistant(self, chat_id)
audio_stream_quality = await get_audio_bitrate(chat_id)
video_stream_quality = await get_video_bitrate(chat_id)
stream = (
AudioVideoPiped(
link,
audio_parameters=audio_stream_quality,
video_parameters=video_stream_quality,
)
if video
else AudioPiped(
link, audio_parameters=audio_stream_quality
)
)
try:
await assistant.join_group_call(
chat_id,
stream,
stream_type=StreamType().pulse_stream,
)
except NoActiveGroupCall:
try:
await self.join_assistant(original_chat_id, chat_id)
except Exception as e:
raise e
try:
await assistant.join_group_call(
chat_id,
stream,
stream_type=StreamType().pulse_stream,
)
except Exception as e:
raise AssistantErr(
"**No Active Voice Chat Found**\n\nPlease make sure group's voice chat is enabled. If already enabled, please end it and start fresh voice chat again and if the problem continues, try /restart"
)
except AlreadyJoinedError:
raise AssistantErr(
"**Assistant Already in Voice Chat**\n\nSystems have detected that assistant is already there in the voice chat, this issue generally comes when you play 2 queries together.\n\nIf assistant is not present in voice chat, please end voice chat and start fresh voice chat again and if the problem continues, try /restart"
)
except TelegramServerError:
raise AssistantErr(
"**Telegram Server Error**\n\nTelegram is having some internal server problems, Please try playing again.\n\n If this problem keeps coming everytime, please end your voice chat and start fresh voice chat again."
)
await add_active_chat(chat_id)
await mute_off(chat_id)
await music_on(chat_id)
if video:
await add_active_video_chat(chat_id)
if await is_autoend():
counter[chat_id] = {}
users = len(await assistant.get_participants(chat_id))
if users == 1:
autoend[chat_id] = datetime.now() + timedelta(
minutes=AUTO_END_TIME
)
async def change_stream(self, client, chat_id):
check = db.get(chat_id)
popped = None
loop = await get_loop(chat_id)
try:
if loop == 0:
popped = check.pop(0)
else:
loop = loop - 1
await set_loop(chat_id, loop)
if popped:
if config.AUTO_DOWNLOADS_CLEAR == str(True):
await auto_clean(popped)
if not check:
await _clear_(chat_id)
return await client.leave_group_call(chat_id)
except:
try:
await _clear_(chat_id)
return await client.leave_group_call(chat_id)
except:
return
else:
queued = check[0]["file"]
language = await get_lang(chat_id)
_ = get_string(language)
title = (check[0]["title"]).title()
user = check[0]["by"]
original_chat_id = check[0]["chat_id"]
streamtype = check[0]["streamtype"]
audio_stream_quality = await get_audio_bitrate(chat_id)
video_stream_quality = await get_video_bitrate(chat_id)
videoid = check[0]["vidid"]
check[0]["played"] = 0
if "live_" in queued:
n, link = await YouTube.video(videoid, True)
if n == 0:
return await app.send_message(
original_chat_id,
text=_["call_9"],
)
stream = (
AudioVideoPiped(
link,
audio_parameters=audio_stream_quality,
video_parameters=video_stream_quality,
)
if str(streamtype) == "video"
else AudioPiped(
link, audio_parameters=audio_stream_quality
)
)
try:
await client.change_stream(chat_id, stream)
except Exception:
return await app.send_message(
original_chat_id,
text=_["call_9"],
)
img = await gen_thumb(videoid)
button = telegram_markup(_, chat_id)
run = await app.send_photo(
original_chat_id,
photo=img,
caption=_["stream_1"].format(
user,
f"https://t.me/{app.username}?start=info_{videoid}",
),
reply_markup=InlineKeyboardMarkup(button),
)
db[chat_id][0]["mystic"] = run
db[chat_id][0]["markup"] = "tg"
elif "vid_" in queued:
mystic = await app.send_message(
original_chat_id, _["call_10"]
)
try:
file_path, direct = await YouTube.download(
videoid,
mystic,
videoid=True,
video=True
if str(streamtype) == "video"
else False,
)
except:
return await mystic.edit_text(
_["call_9"], disable_web_page_preview=True
)
stream = (
AudioVideoPiped(
file_path,
audio_parameters=audio_stream_quality,
video_parameters=video_stream_quality,
)
if str(streamtype) == "video"
else AudioPiped(
file_path,
audio_parameters=audio_stream_quality,
)
)
try:
await client.change_stream(chat_id, stream)
except Exception:
return await app.send_message(
original_chat_id,
text=_["call_9"],
)
img = await gen_thumb(videoid)
button = stream_markup(_, videoid, chat_id)
await mystic.delete()
run = await app.send_photo(
original_chat_id,
photo=img,
caption=_["stream_1"].format(
user,
f"https://t.me/{app.username}?start=info_{videoid}",
),
reply_markup=InlineKeyboardMarkup(button),
)
db[chat_id][0]["mystic"] = run
db[chat_id][0]["markup"] = "stream"
elif "index_" in queued:
stream = (
AudioVideoPiped(
videoid,
audio_parameters=audio_stream_quality,
video_parameters=video_stream_quality,
)
if str(streamtype) == "video"
else AudioPiped(
videoid, audio_parameters=audio_stream_quality
)
)
try:
await client.change_stream(chat_id, stream)
except Exception:
return await app.send_message(
original_chat_id,
text=_["call_9"],
)
button = telegram_markup(_, chat_id)
run = await app.send_photo(
original_chat_id,
photo=config.STREAM_IMG_URL,
caption=_["stream_2"].format(user),
reply_markup=InlineKeyboardMarkup(button),
)
db[chat_id][0]["mystic"] = run
db[chat_id][0]["markup"] = "tg"
else:
stream = (
AudioVideoPiped(
queued,
audio_parameters=audio_stream_quality,
video_parameters=video_stream_quality,
)
if str(streamtype) == "video"
else AudioPiped(
queued, audio_parameters=audio_stream_quality
)
)
try:
await client.change_stream(chat_id, stream)
except Exception:
return await app.send_message(
original_chat_id,
text=_["call_9"],
)
if videoid == "telegram":
button = telegram_markup(_, chat_id)
run = await app.send_photo(
original_chat_id,
photo=config.TELEGRAM_AUDIO_URL
if str(streamtype) == "audio"
else config.TELEGRAM_VIDEO_URL,
caption=_["stream_3"].format(
title, check[0]["dur"], user
),
reply_markup=InlineKeyboardMarkup(button),
)
db[chat_id][0]["mystic"] = run
db[chat_id][0]["markup"] = "tg"
elif videoid == "soundcloud":
button = telegram_markup(_, chat_id)
run = await app.send_photo(
original_chat_id,
photo=config.SOUNCLOUD_IMG_URL,
caption=_["stream_3"].format(
title, check[0]["dur"], user
),
reply_markup=InlineKeyboardMarkup(button),
)
db[chat_id][0]["mystic"] = run
db[chat_id][0]["markup"] = "tg"
else:
img = await gen_thumb(videoid)
button = stream_markup(_, videoid, chat_id)
run = await app.send_photo(
original_chat_id,
photo=img,
caption=_["stream_1"].format(
user,
f"https://t.me/{app.username}?start=info_{videoid}",
),
reply_markup=InlineKeyboardMarkup(button),
)
db[chat_id][0]["mystic"] = run
db[chat_id][0]["markup"] = "stream"
async def ping(self):
pings = []
if config.STRING1:
pings.append(await self.one.ping)
if config.STRING2:
pings.append(await self.two.ping)
if config.STRING3:
pings.append(await self.three.ping)
if config.STRING4:
pings.append(await self.four.ping)
if config.STRING5:
pings.append(await self.five.ping)
return str(round(sum(pings) / len(pings), 3))
async def start(self):
LOGGER(__name__).info("Starting PyTgCalls Client\n")
if config.STRING1:
await self.one.start()
if config.STRING2:
await self.two.start()
if config.STRING3:
await self.three.start()
if config.STRING4:
await self.four.start()
if config.STRING5:
await self.five.start()
async def decorators(self):
@self.one.on_kicked()
@self.two.on_kicked()
@self.three.on_kicked()
@self.four.on_kicked()
@self.five.on_kicked()
@self.one.on_closed_voice_chat()
@self.two.on_closed_voice_chat()
@self.three.on_closed_voice_chat()
@self.four.on_closed_voice_chat()
@self.five.on_closed_voice_chat()
@self.one.on_left()
@self.two.on_left()
@self.three.on_left()
@self.four.on_left()
@self.five.on_left()
async def stream_services_handler(_, chat_id: int):
await self.stop_stream(chat_id)
@self.one.on_stream_end()
@self.two.on_stream_end()
@self.three.on_stream_end()
@self.four.on_stream_end()
@self.five.on_stream_end()
async def stream_end_handler1(client, update: Update):
if not isinstance(update, StreamAudioEnded):
return
await self.change_stream(client, update.chat_id)
@self.one.on_participants_change()
@self.two.on_participants_change()
@self.three.on_participants_change()
@self.four.on_participants_change()
@self.five.on_participants_change()
async def participants_change_handler(client, update: Update):
if not isinstance(
update, JoinedGroupCallParticipant
) and not isinstance(update, LeftGroupCallParticipant):
return
chat_id = update.chat_id
users = counter.get(chat_id)
if not users:
try:
got = len(await client.get_participants(chat_id))
except:
return
counter[chat_id] = got
if got == 1:
autoend[chat_id] = datetime.now() + timedelta(
minutes=AUTO_END_TIME
)
return
autoend[chat_id] = {}
else:
final = (
users + 1
if isinstance(update, JoinedGroupCallParticipant)
else users - 1
)
counter[chat_id] = final
if final == 1:
autoend[chat_id] = datetime.now() + timedelta(
minutes=AUTO_END_TIME
)
return
autoend[chat_id] = {}
Yukki = Call() | 0.44071 | 0.061933 |
import itertools
import gpuscheduler
import argparse
import os
import uuid
import hashlib
import glob
from itertools import product
from torch.optim.lr_scheduler import OneCycleLR
from os.path import join
parser = argparse.ArgumentParser(description='Compute script.')
parser.add_argument('--dry', action='store_true')
parser.add_argument('--verbose', action='store_true')
args = parser.parse_args()
cmd = 'MKL_THREADING_LAYER=GNU python main.py --data cifar --sde-argconfig ~/git/sde/config/args_config.txt'
args2 = {}
name = 'grid_full7'
ckp_name = name
logfolder = 'sde/{0}/'.format(name)
#time_hours = 24*2
cores_per_job = 5
mem = 32
num_seeds = 10
seed_offset = 0
constraint = ''
gpus = 1
#account = 'cse'
#account = 'stf'
#account = 'ark'
#partition = 'scavenge'
#partition = 'scavenge,learnfair'
partition = 'learnfair'
#partition = 'uninterrupted'
#partition = 'dev'
change_dir = 'sparse_learning/mnist_cifar/'
repo = 'sparse_learning'
exclude = ''
s = gpuscheduler.HyakScheduler(verbose=args.verbose, account='', partition=partition, use_gres=False)
#s = gpuscheduler.SshScheduler(verbose=args.verbose)
for key, value in args2.items():
cmd = cmd + ' --{0} {1}'.format(key, value)
folder = './hook_data/cifar10-{0}-{1}-{2}'
fp16 = False
args3 = {}
args3['sde-subset-size'] = [0.1, 1.0]
args3['model'] = ['wrn-16-8', 'wrn-22-8', 'alexnet-s', 'alexnet-b','models-dense','models-efficient','models-google','models-mobile','models-regnext-200','models-regnext-400','models-preact-18 --lr 0.01','models-preact-50 --lr 0.01','models-resnet-18','models-resnet-50 --lr 0.01','models-resnext-2','models-shufflev2','models-dpn-26 --lr 0.01', 'models-mobilev2']
args4 = []
for epoch, metric in product([25, 200], ['full']):
folder_name = folder.format(epoch, metric, name)
args4.append(' --epochs {0} --metric {1} --sde-folder {2} '.format(epoch, metric, folder_name))
args5 = {}
args5['wrn'] = {'dropout' : ['0.3 --fp16']}
args5['models-'] = {'fp16' : ['']}
time_hours = 12
time_minutes = 0
args_prod = []
for key, values in args3.items():
if len(key) == 0:
keyvalues = [' --{0}'.format(v) if len(v) > 0 else '{0}'.format(v) for v in values]
else:
keyvalues = [' --{0} {1}'.format(key, v) for v in values]
args_prod.append(keyvalues)
if len(args_prod) >= 2:
args_prod = list(product(*args_prod))
else:
new_args = []
if len(args_prod) > 0:
for arg in args_prod[0]:
new_args.append([arg])
args_prod = new_args
jobs = []
if len(args4) == 0: args4.append('')
for seed in range(num_seeds):
seed = seed + seed_offset
for arg4 in args4:
if len(args_prod) == 0: args_prod.append(('', ''))
for i, values in enumerate(args_prod):
job_cmd = cmd + arg4
for val in values:
job_cmd += ' {0}' .format(val)
#job_cmd += ' --checkpoint /checkpoint/timdettmers/{1}/{0}/model.pt'.format(hashlib.md5(str(job_cmd).encode('utf-8')).hexdigest(), ckp_name)
if not fp16: job_cmd = job_cmd.replace('--fp16', '')
if any([k in job_cmd for k in args5.keys()]):
for substr, pdict in args5.items():
if substr in job_cmd:
for key, values in pdict.items():
for v in values:
job_cmd5 = job_cmd + ' --{0} {1}'.format(key, v)
job_cmd5 = job_cmd5 + ' --seed {0}'.format(seed)
jobs.append(job_cmd5)
s.add_job(logfolder, repo, change_dir, job_cmd5, time_hours, fp16, cores=cores_per_job, mem=mem, constraint=constraint, exclude=exclude, time_minutes=time_minutes, gpus=gpus)
else:
job_cmd = job_cmd + ' --seed {0}'.format(seed)
jobs.append(job_cmd)
s.add_job(logfolder, repo, change_dir, job_cmd, time_hours, fp16, cores=cores_per_job, mem=mem, constraint=constraint, exclude=exclude, time_minutes=time_minutes, gpus=gpus)
if args.dry:
for job in jobs:
print(job)
print('total jobs', len(jobs))
print('Jobs will be written to: {0}'.format(logfolder))
print('Jobs will be run on: {0}'.format(partition))
if not args.dry:
s.run_jobs() | scripts/sde/grid_search.py | import itertools
import gpuscheduler
import argparse
import os
import uuid
import hashlib
import glob
from itertools import product
from torch.optim.lr_scheduler import OneCycleLR
from os.path import join
parser = argparse.ArgumentParser(description='Compute script.')
parser.add_argument('--dry', action='store_true')
parser.add_argument('--verbose', action='store_true')
args = parser.parse_args()
cmd = 'MKL_THREADING_LAYER=GNU python main.py --data cifar --sde-argconfig ~/git/sde/config/args_config.txt'
args2 = {}
name = 'grid_full7'
ckp_name = name
logfolder = 'sde/{0}/'.format(name)
#time_hours = 24*2
cores_per_job = 5
mem = 32
num_seeds = 10
seed_offset = 0
constraint = ''
gpus = 1
#account = 'cse'
#account = 'stf'
#account = 'ark'
#partition = 'scavenge'
#partition = 'scavenge,learnfair'
partition = 'learnfair'
#partition = 'uninterrupted'
#partition = 'dev'
change_dir = 'sparse_learning/mnist_cifar/'
repo = 'sparse_learning'
exclude = ''
s = gpuscheduler.HyakScheduler(verbose=args.verbose, account='', partition=partition, use_gres=False)
#s = gpuscheduler.SshScheduler(verbose=args.verbose)
for key, value in args2.items():
cmd = cmd + ' --{0} {1}'.format(key, value)
folder = './hook_data/cifar10-{0}-{1}-{2}'
fp16 = False
args3 = {}
args3['sde-subset-size'] = [0.1, 1.0]
args3['model'] = ['wrn-16-8', 'wrn-22-8', 'alexnet-s', 'alexnet-b','models-dense','models-efficient','models-google','models-mobile','models-regnext-200','models-regnext-400','models-preact-18 --lr 0.01','models-preact-50 --lr 0.01','models-resnet-18','models-resnet-50 --lr 0.01','models-resnext-2','models-shufflev2','models-dpn-26 --lr 0.01', 'models-mobilev2']
args4 = []
for epoch, metric in product([25, 200], ['full']):
folder_name = folder.format(epoch, metric, name)
args4.append(' --epochs {0} --metric {1} --sde-folder {2} '.format(epoch, metric, folder_name))
args5 = {}
args5['wrn'] = {'dropout' : ['0.3 --fp16']}
args5['models-'] = {'fp16' : ['']}
time_hours = 12
time_minutes = 0
args_prod = []
for key, values in args3.items():
if len(key) == 0:
keyvalues = [' --{0}'.format(v) if len(v) > 0 else '{0}'.format(v) for v in values]
else:
keyvalues = [' --{0} {1}'.format(key, v) for v in values]
args_prod.append(keyvalues)
if len(args_prod) >= 2:
args_prod = list(product(*args_prod))
else:
new_args = []
if len(args_prod) > 0:
for arg in args_prod[0]:
new_args.append([arg])
args_prod = new_args
jobs = []
if len(args4) == 0: args4.append('')
for seed in range(num_seeds):
seed = seed + seed_offset
for arg4 in args4:
if len(args_prod) == 0: args_prod.append(('', ''))
for i, values in enumerate(args_prod):
job_cmd = cmd + arg4
for val in values:
job_cmd += ' {0}' .format(val)
#job_cmd += ' --checkpoint /checkpoint/timdettmers/{1}/{0}/model.pt'.format(hashlib.md5(str(job_cmd).encode('utf-8')).hexdigest(), ckp_name)
if not fp16: job_cmd = job_cmd.replace('--fp16', '')
if any([k in job_cmd for k in args5.keys()]):
for substr, pdict in args5.items():
if substr in job_cmd:
for key, values in pdict.items():
for v in values:
job_cmd5 = job_cmd + ' --{0} {1}'.format(key, v)
job_cmd5 = job_cmd5 + ' --seed {0}'.format(seed)
jobs.append(job_cmd5)
s.add_job(logfolder, repo, change_dir, job_cmd5, time_hours, fp16, cores=cores_per_job, mem=mem, constraint=constraint, exclude=exclude, time_minutes=time_minutes, gpus=gpus)
else:
job_cmd = job_cmd + ' --seed {0}'.format(seed)
jobs.append(job_cmd)
s.add_job(logfolder, repo, change_dir, job_cmd, time_hours, fp16, cores=cores_per_job, mem=mem, constraint=constraint, exclude=exclude, time_minutes=time_minutes, gpus=gpus)
if args.dry:
for job in jobs:
print(job)
print('total jobs', len(jobs))
print('Jobs will be written to: {0}'.format(logfolder))
print('Jobs will be run on: {0}'.format(partition))
if not args.dry:
s.run_jobs() | 0.284675 | 0.085404 |
import asyncio
import datetime
import logging
import os
from aiohttp import web
from .constants import *
class EternalServer:
SHUTDOWN_TIMEOUT = 5
def __init__(self, *, address=None, port=8080, ssl_context=None,
mode=OperationMode.clock, buffer_size=128*2**10, loop=None):
self._loop = loop if loop is not None else asyncio.get_event_loop()
self._logger = logging.getLogger(self.__class__.__name__)
self._address = address
self._port = port
self._ssl_context = ssl_context
self._mode = mode
self._int_fut = self._loop.create_future()
self._shutdown = asyncio.ensure_future(self._int_fut, loop=self._loop)
self._handler = {
OperationMode.clock: self.handler_clock,
OperationMode.null: self.handler_null,
OperationMode.newline: self.handler_newline,
OperationMode.urandom: self.handler_urandom,
OperationMode.slow_newline: self.handler_slow_newline,
}[self._mode]
self.ZEROES=bytearray(buffer_size)
self.NEWLINES=bytearray(0xA for _ in range(buffer_size))
self._buffer_size = buffer_size
async def stop(self):
try:
self._int_fut.set_result(None)
except asyncio.InvalidStateError:
pass
else:
await self._server.shutdown()
await self._site.stop()
await self._runner.cleanup()
async def run(self):
await self._shutdown
async def _guarded_run(self, awaitable):
task = asyncio.ensure_future(awaitable)
try:
_, pending = await asyncio.wait((self._shutdown, task),
return_when=asyncio.FIRST_COMPLETED)
except asyncio.CancelledError:
task.cancel()
raise
if task in pending:
task.cancel()
return None
else:
return task.result()
async def common_handler(self, request):
peer_addr = request.transport.get_extra_info('peername')
self._logger.info("Client %s connected.", str(peer_addr))
try:
return await self._handler(request)
finally:
self._logger.info("Client %s disconnected.", str(peer_addr))
async def handler_clock(self, request):
resp = web.StreamResponse(headers={'Content-Type': 'text/plain'})
resp.enable_chunked_encoding()
await resp.prepare(request)
while not self._shutdown.done():
dt = datetime.datetime.utcnow()
text = dt.strftime("%m %b %H:%M:%S.%f\n").encode('ascii')
await self._guarded_run(resp.write(text))
ts = dt.timestamp()
sleep_time = max(0, 1 - datetime.datetime.utcnow().timestamp() + ts)
await self._guarded_run(asyncio.sleep(sleep_time))
return resp
async def handler_null(self, request):
resp = web.StreamResponse(
headers={'Content-Type': 'application/octet-stream'})
resp.enable_chunked_encoding()
await resp.prepare(request)
while not self._shutdown.done():
await self._guarded_run(resp.write(self.ZEROES))
return resp
async def handler_newline(self, request):
resp = web.StreamResponse(
headers={'Content-Type': 'text/plain'})
resp.enable_chunked_encoding()
await resp.prepare(request)
while not self._shutdown.done():
await self._guarded_run(resp.write(self.NEWLINES))
return resp
async def handler_urandom(self, request):
resp = web.StreamResponse(
headers={'Content-Type': 'application/octet-stream'})
resp.enable_chunked_encoding()
await resp.prepare(request)
while not self._shutdown.done():
await self._guarded_run(resp.write(os.urandom(self._buffer_size)))
return resp
async def handler_slow_newline(self, request):
resp = web.StreamResponse(headers={'Content-Type': 'text/plain'})
resp.enable_chunked_encoding()
await resp.prepare(request)
while not self._shutdown.done():
dt = datetime.datetime.utcnow()
await self._guarded_run(resp.write(b'\n'))
ts = dt.timestamp()
sleep_time = max(0, 1 - datetime.datetime.utcnow().timestamp() + ts)
await self._guarded_run(asyncio.sleep(sleep_time))
return resp
async def setup(self):
self._server = web.Server(self.common_handler)
self._runner = web.ServerRunner(self._server)
await self._runner.setup()
self._site = web.TCPSite(self._runner, self._address, self._port,
ssl_context=self._ssl_context,
shutdown_timeout=self.SHUTDOWN_TIMEOUT)
await self._site.start()
self._logger.info("Server ready.") | http_tarpit/server.py | import asyncio
import datetime
import logging
import os
from aiohttp import web
from .constants import *
class EternalServer:
SHUTDOWN_TIMEOUT = 5
def __init__(self, *, address=None, port=8080, ssl_context=None,
mode=OperationMode.clock, buffer_size=128*2**10, loop=None):
self._loop = loop if loop is not None else asyncio.get_event_loop()
self._logger = logging.getLogger(self.__class__.__name__)
self._address = address
self._port = port
self._ssl_context = ssl_context
self._mode = mode
self._int_fut = self._loop.create_future()
self._shutdown = asyncio.ensure_future(self._int_fut, loop=self._loop)
self._handler = {
OperationMode.clock: self.handler_clock,
OperationMode.null: self.handler_null,
OperationMode.newline: self.handler_newline,
OperationMode.urandom: self.handler_urandom,
OperationMode.slow_newline: self.handler_slow_newline,
}[self._mode]
self.ZEROES=bytearray(buffer_size)
self.NEWLINES=bytearray(0xA for _ in range(buffer_size))
self._buffer_size = buffer_size
async def stop(self):
try:
self._int_fut.set_result(None)
except asyncio.InvalidStateError:
pass
else:
await self._server.shutdown()
await self._site.stop()
await self._runner.cleanup()
async def run(self):
await self._shutdown
async def _guarded_run(self, awaitable):
task = asyncio.ensure_future(awaitable)
try:
_, pending = await asyncio.wait((self._shutdown, task),
return_when=asyncio.FIRST_COMPLETED)
except asyncio.CancelledError:
task.cancel()
raise
if task in pending:
task.cancel()
return None
else:
return task.result()
async def common_handler(self, request):
peer_addr = request.transport.get_extra_info('peername')
self._logger.info("Client %s connected.", str(peer_addr))
try:
return await self._handler(request)
finally:
self._logger.info("Client %s disconnected.", str(peer_addr))
async def handler_clock(self, request):
resp = web.StreamResponse(headers={'Content-Type': 'text/plain'})
resp.enable_chunked_encoding()
await resp.prepare(request)
while not self._shutdown.done():
dt = datetime.datetime.utcnow()
text = dt.strftime("%m %b %H:%M:%S.%f\n").encode('ascii')
await self._guarded_run(resp.write(text))
ts = dt.timestamp()
sleep_time = max(0, 1 - datetime.datetime.utcnow().timestamp() + ts)
await self._guarded_run(asyncio.sleep(sleep_time))
return resp
async def handler_null(self, request):
resp = web.StreamResponse(
headers={'Content-Type': 'application/octet-stream'})
resp.enable_chunked_encoding()
await resp.prepare(request)
while not self._shutdown.done():
await self._guarded_run(resp.write(self.ZEROES))
return resp
async def handler_newline(self, request):
resp = web.StreamResponse(
headers={'Content-Type': 'text/plain'})
resp.enable_chunked_encoding()
await resp.prepare(request)
while not self._shutdown.done():
await self._guarded_run(resp.write(self.NEWLINES))
return resp
async def handler_urandom(self, request):
resp = web.StreamResponse(
headers={'Content-Type': 'application/octet-stream'})
resp.enable_chunked_encoding()
await resp.prepare(request)
while not self._shutdown.done():
await self._guarded_run(resp.write(os.urandom(self._buffer_size)))
return resp
async def handler_slow_newline(self, request):
resp = web.StreamResponse(headers={'Content-Type': 'text/plain'})
resp.enable_chunked_encoding()
await resp.prepare(request)
while not self._shutdown.done():
dt = datetime.datetime.utcnow()
await self._guarded_run(resp.write(b'\n'))
ts = dt.timestamp()
sleep_time = max(0, 1 - datetime.datetime.utcnow().timestamp() + ts)
await self._guarded_run(asyncio.sleep(sleep_time))
return resp
async def setup(self):
self._server = web.Server(self.common_handler)
self._runner = web.ServerRunner(self._server)
await self._runner.setup()
self._site = web.TCPSite(self._runner, self._address, self._port,
ssl_context=self._ssl_context,
shutdown_timeout=self.SHUTDOWN_TIMEOUT)
await self._site.start()
self._logger.info("Server ready.") | 0.362518 | 0.051012 |
# Copyright (c) 2020. Lightly AG and its affiliates.
# All Rights Reserved
from lightly.api.utils import getenv, get_request, post_request
from typing import Union
def _prefix(dataset_id: Union[str, None] = None,
sample_id: Union[str, None] = None,
*args, **kwargs):
"""Returns the prefix for the samples routes.
Args:
dataset_id:
Identifier of the dataset.
sample_id:
Identifier of the sample.
"""
server_location = getenv(
'LIGHTLY_SERVER_LOCATION',
'https://api.lightly.ai'
)
prefix = server_location + '/users/datasets'
if dataset_id is None:
prefix = prefix + '/samples'
else:
prefix = prefix + '/' + dataset_id + '/samples'
if sample_id is None:
return prefix
else:
return prefix + '/' + sample_id
def get_presigned_upload_url(filename: str,
dataset_id: str,
sample_id: str,
token: str) -> str:
"""Creates and returns a signed url to upload an image to a dataset.
Args:
filename:
Filename of the image to upload.
dataset_id:
Identifier of the dataset.
sample_id:
Identifier of the sample.
token:
The token for authenticating the request.
Returns:
A string containing the signed url.
Raises:
RuntimeError if requesting signed url failed.
"""
dst_url = _prefix(dataset_id=dataset_id, sample_id=sample_id) + '/writeurl'
payload = {
'fileName': filename,
'token': token
}
response = get_request(dst_url, params=payload)
signed_url = response.json()['signedWriteUrl']
return signed_url
def post(filename: str,
thumbname: str,
metadata: str,
dataset_id: str,
token: str):
"""Uploads a sample and its metadata to the servers.
Args:
filename:
Filename of the sample.
thumbname:
Filename of thumbnail if it exists.
metadata:
Dictionary containing metadata of the sample.
dataset_id:
Identifier of the dataset.
token:
The token for authenticating the request.
Returns:
Sample id of the uploaded sample.
Raises:
RuntimeError if post request failed.
"""
dst_url = _prefix(dataset_id=dataset_id)
payload = {
'sample': {
'fileName': filename,
'meta': metadata,
},
'token': token
}
# fix url, TODO: fix api instead
dst_url += '/'
if thumbname is not None:
payload['sample']['thumbName'] = thumbname
response = post_request(dst_url, json=payload)
sample_id = response.json()['sampleId']
return sample_id | lightly/api/routes/users/datasets/samples/service.py |
# Copyright (c) 2020. Lightly AG and its affiliates.
# All Rights Reserved
from lightly.api.utils import getenv, get_request, post_request
from typing import Union
def _prefix(dataset_id: Union[str, None] = None,
sample_id: Union[str, None] = None,
*args, **kwargs):
"""Returns the prefix for the samples routes.
Args:
dataset_id:
Identifier of the dataset.
sample_id:
Identifier of the sample.
"""
server_location = getenv(
'LIGHTLY_SERVER_LOCATION',
'https://api.lightly.ai'
)
prefix = server_location + '/users/datasets'
if dataset_id is None:
prefix = prefix + '/samples'
else:
prefix = prefix + '/' + dataset_id + '/samples'
if sample_id is None:
return prefix
else:
return prefix + '/' + sample_id
def get_presigned_upload_url(filename: str,
dataset_id: str,
sample_id: str,
token: str) -> str:
"""Creates and returns a signed url to upload an image to a dataset.
Args:
filename:
Filename of the image to upload.
dataset_id:
Identifier of the dataset.
sample_id:
Identifier of the sample.
token:
The token for authenticating the request.
Returns:
A string containing the signed url.
Raises:
RuntimeError if requesting signed url failed.
"""
dst_url = _prefix(dataset_id=dataset_id, sample_id=sample_id) + '/writeurl'
payload = {
'fileName': filename,
'token': token
}
response = get_request(dst_url, params=payload)
signed_url = response.json()['signedWriteUrl']
return signed_url
def post(filename: str,
thumbname: str,
metadata: str,
dataset_id: str,
token: str):
"""Uploads a sample and its metadata to the servers.
Args:
filename:
Filename of the sample.
thumbname:
Filename of thumbnail if it exists.
metadata:
Dictionary containing metadata of the sample.
dataset_id:
Identifier of the dataset.
token:
The token for authenticating the request.
Returns:
Sample id of the uploaded sample.
Raises:
RuntimeError if post request failed.
"""
dst_url = _prefix(dataset_id=dataset_id)
payload = {
'sample': {
'fileName': filename,
'meta': metadata,
},
'token': token
}
# fix url, TODO: fix api instead
dst_url += '/'
if thumbname is not None:
payload['sample']['thumbName'] = thumbname
response = post_request(dst_url, json=payload)
sample_id = response.json()['sampleId']
return sample_id | 0.835484 | 0.238445 |
import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.optim import Adam
from sklearn.preprocessing import MinMaxScaler
# Source: https://github.com/techshot25/Autoencoders
class Autoencoder(nn.Module):
"""Makes the main denoising autoencoder
Parameters
----------
in_shape [int] : input shape
enc_shape [int] : desired encoded shape
"""
def __init__(self, in_shape, enc_shape):
super(Autoencoder, self).__init__()
self.device = ('cuda' if torch.cuda.is_available() else 'cpu')
self.encode = nn.Sequential(
nn.Linear(in_shape, 128),
nn.ReLU(True),
nn.Dropout(0.2),
nn.Linear(128, 64),
nn.ReLU(True),
nn.Dropout(0.2),
nn.Linear(64, enc_shape),
)
self.decode = nn.Sequential(
nn.BatchNorm1d(enc_shape),
nn.Linear(enc_shape, 64),
nn.ReLU(True),
nn.Dropout(0.2),
nn.Linear(64, 128),
nn.ReLU(True),
nn.Dropout(0.2),
nn.Linear(128, in_shape)
)
self.scaler = MinMaxScaler()
self.error = nn.MSELoss()
self.optimizer = Adam(self.parameters())
def forward(self, x):
x = self.encode(x)
x = self.decode(x)
return x
def train_model(self, n_epochs, x, verbose = True):
self.train()
for epoch in range(1, n_epochs + 1):
self.optimizer.zero_grad()
output = self(x)
loss = self.error(output, x)
loss.backward()
self.optimizer.step()
if verbose:
if epoch % int(0.1*n_epochs) == 0:
print(f'AE epoch {epoch} \t Loss: {loss.item():.4g}')
print('\n')
def encode_min(self, x):
x = self.scaler.fit_transform([x])
x = self.encode(torch.from_numpy(x).to(self.device))
x = x.cpu().detach().numpy().tolist()[0]
return x | autoencoder.py | import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.optim import Adam
from sklearn.preprocessing import MinMaxScaler
# Source: https://github.com/techshot25/Autoencoders
class Autoencoder(nn.Module):
"""Makes the main denoising autoencoder
Parameters
----------
in_shape [int] : input shape
enc_shape [int] : desired encoded shape
"""
def __init__(self, in_shape, enc_shape):
super(Autoencoder, self).__init__()
self.device = ('cuda' if torch.cuda.is_available() else 'cpu')
self.encode = nn.Sequential(
nn.Linear(in_shape, 128),
nn.ReLU(True),
nn.Dropout(0.2),
nn.Linear(128, 64),
nn.ReLU(True),
nn.Dropout(0.2),
nn.Linear(64, enc_shape),
)
self.decode = nn.Sequential(
nn.BatchNorm1d(enc_shape),
nn.Linear(enc_shape, 64),
nn.ReLU(True),
nn.Dropout(0.2),
nn.Linear(64, 128),
nn.ReLU(True),
nn.Dropout(0.2),
nn.Linear(128, in_shape)
)
self.scaler = MinMaxScaler()
self.error = nn.MSELoss()
self.optimizer = Adam(self.parameters())
def forward(self, x):
x = self.encode(x)
x = self.decode(x)
return x
def train_model(self, n_epochs, x, verbose = True):
self.train()
for epoch in range(1, n_epochs + 1):
self.optimizer.zero_grad()
output = self(x)
loss = self.error(output, x)
loss.backward()
self.optimizer.step()
if verbose:
if epoch % int(0.1*n_epochs) == 0:
print(f'AE epoch {epoch} \t Loss: {loss.item():.4g}')
print('\n')
def encode_min(self, x):
x = self.scaler.fit_transform([x])
x = self.encode(torch.from_numpy(x).to(self.device))
x = x.cpu().detach().numpy().tolist()[0]
return x | 0.956654 | 0.437703 |
import pandas as pd
class Emissions:
def __init__(self):
ds = pd.read_csv('tri.csv')
df = pd.DataFrame(ds)
self.data = pd.DataFrame(columns=['Facility','Sector','FRS-ID','Latitude','Longitude','Chemical','Emissions','Off-Site','Production-Waste'])
lf = []
ls = []
lfi = []
lla = []
llo = []
lc = []
le = []
lo = []
lp = []
for i in range(len(df)):
row = df.iloc[i]
county = row[6]
caa = row[37]
car = row[41]
if pd.isna(row[113]) == True:
row[113] = 0
emis = row[100] + row[101] + row[103] + row[104] + row[113]
if county == 'LOS ANGELES':
if (caa == 'YES') or (car == 'YES'):
if emis > 1:
frsid = row[2]
fac = row[3]
lat = row[11]
lon = row[12]
sect = row[19]
chem = row[33]
os = row[81]
pw = row[112]
lf.append(fac)
ls.append(sect)
lfi.append(frsid)
lla.append(lat)
llo.append(lon)
lc.append(chem)
le.append(emis)
lo.append(os)
lp.append(pw)
self.data['Facility'] = lf
self.data['Sector'] = ls
self.data['FRS-ID'] = lfi
self.data['Latitude'] = lla
self.data['Longitude'] = llo
self.data['Chemical'] = lc
self.data['Emissions'] = le
self.data['Off-Site'] = lo
self.data['Production-Waste'] = lp
self.facilities = []
for i in range(len(self.data)):
row = self.data.iloc[i]
fn = row[0]
if fn not in self.facilities:
self.facilities.append(fn)
class Asthma:
def __init__(self):
ds = pd.read_csv('asthma-ed.csv')
df = pd.DataFrame(ds)
self.geometry = pd.DataFrame(columns=['Zip','Visits','Age'])
lzip = []
lvisit = []
lage = []
for i in range(len(df)):
row = df.iloc[i]
z = row[0]
v = row[1]
ag = row[3]
c = row[4]
if c == 'Los Angeles':
lzip.append(z)
lvisit.append(v)
lage.append(ag)
self.geometry['Zip'] = lzip
self.geometry['Visits'] = lvisit
self.geometry['Age'] = lage | src/pp.py | import pandas as pd
class Emissions:
def __init__(self):
ds = pd.read_csv('tri.csv')
df = pd.DataFrame(ds)
self.data = pd.DataFrame(columns=['Facility','Sector','FRS-ID','Latitude','Longitude','Chemical','Emissions','Off-Site','Production-Waste'])
lf = []
ls = []
lfi = []
lla = []
llo = []
lc = []
le = []
lo = []
lp = []
for i in range(len(df)):
row = df.iloc[i]
county = row[6]
caa = row[37]
car = row[41]
if pd.isna(row[113]) == True:
row[113] = 0
emis = row[100] + row[101] + row[103] + row[104] + row[113]
if county == 'LOS ANGELES':
if (caa == 'YES') or (car == 'YES'):
if emis > 1:
frsid = row[2]
fac = row[3]
lat = row[11]
lon = row[12]
sect = row[19]
chem = row[33]
os = row[81]
pw = row[112]
lf.append(fac)
ls.append(sect)
lfi.append(frsid)
lla.append(lat)
llo.append(lon)
lc.append(chem)
le.append(emis)
lo.append(os)
lp.append(pw)
self.data['Facility'] = lf
self.data['Sector'] = ls
self.data['FRS-ID'] = lfi
self.data['Latitude'] = lla
self.data['Longitude'] = llo
self.data['Chemical'] = lc
self.data['Emissions'] = le
self.data['Off-Site'] = lo
self.data['Production-Waste'] = lp
self.facilities = []
for i in range(len(self.data)):
row = self.data.iloc[i]
fn = row[0]
if fn not in self.facilities:
self.facilities.append(fn)
class Asthma:
def __init__(self):
ds = pd.read_csv('asthma-ed.csv')
df = pd.DataFrame(ds)
self.geometry = pd.DataFrame(columns=['Zip','Visits','Age'])
lzip = []
lvisit = []
lage = []
for i in range(len(df)):
row = df.iloc[i]
z = row[0]
v = row[1]
ag = row[3]
c = row[4]
if c == 'Los Angeles':
lzip.append(z)
lvisit.append(v)
lage.append(ag)
self.geometry['Zip'] = lzip
self.geometry['Visits'] = lvisit
self.geometry['Age'] = lage | 0.12873 | 0.257876 |
from __future__ import print_function
import os
import getpass
from cStringIO import StringIO
try:
import paramiko
except ImportError:
print("Please install paramiko to use SSH connection")
raise
# make these optional so not everyone has to build C binaries
try:
import pandas as pd
if pd.__version__ <= '0.13.1':
raise ImportError
has_pandas = True
except ImportError:
print("Pandas not found or out of date. SSHClient.ps will return str data")
has_pandas = False
class SSHClient(object):
"""
Thin wrapper to connect to client over SSH and execute commands
"""
def __init__(self, host, username='root', password=<PASSWORD>, port=None,
interactive=False):
"""
Parameters
----------
interactive: bool, default False
If True then prompts for password whenever necessary
"""
self.host = host
self.port = port
self.username = username
self.password = password
self.interactive = interactive
self.pwd = '~'
self._con = None
@property
def con(self):
if self._con is None:
self._connect()
return self._con
def _connect(self):
self._con = paramiko.SSHClient()
self._con.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
kwargs = {}
for k in ['username', 'password', 'port']:
if getattr(self, k, None):
kwargs[k] = getattr(self, k)
self._con.connect(self.host, **kwargs)
def chdir(self, new_pwd, relative=True):
"""
Parameters
----------
new_pwd: str,
Directory to change to
relative: bool, default True
If True then the given directory is treated as relative to the
current directory
"""
if new_pwd and self.pwd and relative:
new_pwd = os.path.join(self.pwd, new_pwd)
self.pwd = <PASSWORD>
def add_public_key(self, key_path, validate_password=True):
# TODO unit test. Not sure this works
if validate_password:
self.password = self.validate_password(self.password)
key_path = os.path.expanduser(key_path)
with open(key_path, 'r') as fp:
cmd = 'mkdir -p ~/.ssh && echo "%s" >> ~/.ssh/authorized_keys'
self.wait(cmd % fp.read())
def close(self):
if self._con is not None:
self._con.close()
self._con = None
def exec_command(self, cmd):
"""
Proceed with caution, if you run a command that causes a prompt and then
try to read/print the stdout it's going to block forever
Returns
-------
(stdin, stdout, stderr)
"""
if self.pwd is not None:
cmd = 'cd %s ; %s' % (self.pwd, cmd)
if self.interactive:
print(cmd)
return self.con.exec_command(cmd)
def wait(self, cmd, raise_on_error=True):
"""
Execute command and wait for it to finish. Proceed with caution because
if you run a command that causes a prompt this will hang
"""
_, stdout, stderr = self.exec_command(cmd)
stdout.channel.recv_exit_status()
output = stdout.read()
if self.interactive:
print(output)
errors = stderr.read()
if self.interactive:
print(errors)
if errors and raise_on_error:
raise ValueError(errors)
return output
def nohup(self, cmd):
"""
Execute the command using nohup and &
"""
cmd = "nohup %s &" % cmd
self.exec_command(cmd)
def sudo(self, password=None):
"""
Enter sudo mode
"""
if self.username == 'root':
raise ValueError('Already root user')
password = self.validate_password(password)
stdin, stdout, stderr = self.exec_command('sudo su')
stdin.write("%s\n" % password)
stdin.flush()
errors = stderr.read()
if errors:
raise ValueError(errors)
def validate_password(self, password):
if password is None:
password = self.password
if password is None and self.interactive:
password = get<PASSWORD>pass()
if password is None:
raise ValueError("Password must not be empty")
return password
def unsudo(self):
"""
Assume already in sudo
"""
self.wait('exit')
def apt(self, package_names, raise_on_error=False):
"""
Install specified packages using apt-get. -y options are
automatically used. Waits for command to finish.
Parameters
----------
package_names: list-like of str
raise_on_error: bool, default False
If True then raise ValueError if stderr is not empty
debconf often gives tty error
"""
if isinstance(package_names, basestring):
package_names = [package_names]
cmd = "apt-get install -y %s" % (' '.join(package_names))
return self.wait(cmd, raise_on_error=raise_on_error)
def curl(self, url, raise_on_error=True, **kwargs):
import simplejson as json
def format_param(name):
if len(name) == 1:
prefix = '-'
else:
prefix = '--'
return prefix + name
def format_value(value):
if value is None:
return ''
return json.dumps(value)
options = ['%s %s' % (format_param(k), format_value(v))
for k, v in kwargs.items()]
cmd = 'curl %s "%s"' % (' '.join(options), url)
return self.wait(cmd, raise_on_error=raise_on_error)
def pip(self, package_names, raise_on_error=True):
"""
Install specified python packages using pip. -U option added
Waits for command to finish.
Parameters
----------
package_names: list-like of str
raise_on_error: bool, default True
If True then raise ValueError if stderr is not empty
"""
if isinstance(package_names, basestring):
package_names = [package_names]
cmd = "pip install -U %s" % (' '.join(package_names))
return self.wait(cmd, raise_on_error=raise_on_error)
def pip_freeze(self, raise_on_error=True):
"""
Run `pip freeze` and return output
Waits for command to finish.
"""
return self.wait('pip freeze', raise_on_error=raise_on_error)
def pip_r(self, requirements, raise_on_error=True):
"""
Install all requirements contained in the given file path
Waits for command to finish.
Parameters
----------
requirements: str
Path to requirements.txt
raise_on_error: bool, default True
If True then raise ValueError if stderr is not empty
"""
cmd = "pip install -r %s" % requirements
return self.wait(cmd, raise_on_error=raise_on_error)
def ps(self, args=None, options='', all=True, verbose=True,
as_frame='auto', raise_on_error=True):
if args is None:
args = ''
if all:
args += 'A'
if verbose:
args += 'f'
if len(args) > 0 and args[0] != '-':
args = '-' + args
results = self.wait(('ps %s %s' % (args, options)).strip(),
raise_on_error=raise_on_error)
if as_frame == 'auto':
as_frame = has_pandas
if as_frame:
if not has_pandas:
raise ImportError("Unable to import pandas")
df = pd.read_fwf(StringIO(results))
cmd_loc = df.columns.get_loc('CMD')
if cmd_loc < len(df.columns):
col = cmd_loc.fillna('')
for i in range(cmd_loc + 1, len(df.columns)):
col = col + df.icol(i).fillna('')
df['CMD'] = col
return df
return results
def top(self):
return self.ps('o', TOP_OPTIONS)
def git(self, username, repo, alias=None, token=None):
"""
Parameters
----------
token: str, default None
Assumes you have GITHUB_TOKEN in envvar if None
https://github.com/blog/1270-easier-builds-and-deployments-using-git-
over-https-and-oauth
"""
if alias is None:
alias = repo
if token is None:
token = os.environ.get('GITHUB_TOKEN')
self.wait('mkdir -p %s' % alias)
old_dir = self.pwd
try:
self.chdir(alias, relative=True)
cmd = 'git init && git pull https://%s@github.com/%s/%s.git'
# last line to stderr
return self.wait(cmd % (token, username, repo),
raise_on_error=False)
finally:
self.chdir(old_dir, relative=False)
TOP_OPTIONS = '%cpu,%mem,user,comm' | poseidon/ssh.py | from __future__ import print_function
import os
import getpass
from cStringIO import StringIO
try:
import paramiko
except ImportError:
print("Please install paramiko to use SSH connection")
raise
# make these optional so not everyone has to build C binaries
try:
import pandas as pd
if pd.__version__ <= '0.13.1':
raise ImportError
has_pandas = True
except ImportError:
print("Pandas not found or out of date. SSHClient.ps will return str data")
has_pandas = False
class SSHClient(object):
"""
Thin wrapper to connect to client over SSH and execute commands
"""
def __init__(self, host, username='root', password=<PASSWORD>, port=None,
interactive=False):
"""
Parameters
----------
interactive: bool, default False
If True then prompts for password whenever necessary
"""
self.host = host
self.port = port
self.username = username
self.password = password
self.interactive = interactive
self.pwd = '~'
self._con = None
@property
def con(self):
if self._con is None:
self._connect()
return self._con
def _connect(self):
self._con = paramiko.SSHClient()
self._con.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
kwargs = {}
for k in ['username', 'password', 'port']:
if getattr(self, k, None):
kwargs[k] = getattr(self, k)
self._con.connect(self.host, **kwargs)
def chdir(self, new_pwd, relative=True):
"""
Parameters
----------
new_pwd: str,
Directory to change to
relative: bool, default True
If True then the given directory is treated as relative to the
current directory
"""
if new_pwd and self.pwd and relative:
new_pwd = os.path.join(self.pwd, new_pwd)
self.pwd = <PASSWORD>
def add_public_key(self, key_path, validate_password=True):
# TODO unit test. Not sure this works
if validate_password:
self.password = self.validate_password(self.password)
key_path = os.path.expanduser(key_path)
with open(key_path, 'r') as fp:
cmd = 'mkdir -p ~/.ssh && echo "%s" >> ~/.ssh/authorized_keys'
self.wait(cmd % fp.read())
def close(self):
if self._con is not None:
self._con.close()
self._con = None
def exec_command(self, cmd):
"""
Proceed with caution, if you run a command that causes a prompt and then
try to read/print the stdout it's going to block forever
Returns
-------
(stdin, stdout, stderr)
"""
if self.pwd is not None:
cmd = 'cd %s ; %s' % (self.pwd, cmd)
if self.interactive:
print(cmd)
return self.con.exec_command(cmd)
def wait(self, cmd, raise_on_error=True):
"""
Execute command and wait for it to finish. Proceed with caution because
if you run a command that causes a prompt this will hang
"""
_, stdout, stderr = self.exec_command(cmd)
stdout.channel.recv_exit_status()
output = stdout.read()
if self.interactive:
print(output)
errors = stderr.read()
if self.interactive:
print(errors)
if errors and raise_on_error:
raise ValueError(errors)
return output
def nohup(self, cmd):
"""
Execute the command using nohup and &
"""
cmd = "nohup %s &" % cmd
self.exec_command(cmd)
def sudo(self, password=None):
"""
Enter sudo mode
"""
if self.username == 'root':
raise ValueError('Already root user')
password = self.validate_password(password)
stdin, stdout, stderr = self.exec_command('sudo su')
stdin.write("%s\n" % password)
stdin.flush()
errors = stderr.read()
if errors:
raise ValueError(errors)
def validate_password(self, password):
if password is None:
password = self.password
if password is None and self.interactive:
password = get<PASSWORD>pass()
if password is None:
raise ValueError("Password must not be empty")
return password
def unsudo(self):
"""
Assume already in sudo
"""
self.wait('exit')
def apt(self, package_names, raise_on_error=False):
"""
Install specified packages using apt-get. -y options are
automatically used. Waits for command to finish.
Parameters
----------
package_names: list-like of str
raise_on_error: bool, default False
If True then raise ValueError if stderr is not empty
debconf often gives tty error
"""
if isinstance(package_names, basestring):
package_names = [package_names]
cmd = "apt-get install -y %s" % (' '.join(package_names))
return self.wait(cmd, raise_on_error=raise_on_error)
def curl(self, url, raise_on_error=True, **kwargs):
import simplejson as json
def format_param(name):
if len(name) == 1:
prefix = '-'
else:
prefix = '--'
return prefix + name
def format_value(value):
if value is None:
return ''
return json.dumps(value)
options = ['%s %s' % (format_param(k), format_value(v))
for k, v in kwargs.items()]
cmd = 'curl %s "%s"' % (' '.join(options), url)
return self.wait(cmd, raise_on_error=raise_on_error)
def pip(self, package_names, raise_on_error=True):
"""
Install specified python packages using pip. -U option added
Waits for command to finish.
Parameters
----------
package_names: list-like of str
raise_on_error: bool, default True
If True then raise ValueError if stderr is not empty
"""
if isinstance(package_names, basestring):
package_names = [package_names]
cmd = "pip install -U %s" % (' '.join(package_names))
return self.wait(cmd, raise_on_error=raise_on_error)
def pip_freeze(self, raise_on_error=True):
"""
Run `pip freeze` and return output
Waits for command to finish.
"""
return self.wait('pip freeze', raise_on_error=raise_on_error)
def pip_r(self, requirements, raise_on_error=True):
"""
Install all requirements contained in the given file path
Waits for command to finish.
Parameters
----------
requirements: str
Path to requirements.txt
raise_on_error: bool, default True
If True then raise ValueError if stderr is not empty
"""
cmd = "pip install -r %s" % requirements
return self.wait(cmd, raise_on_error=raise_on_error)
def ps(self, args=None, options='', all=True, verbose=True,
as_frame='auto', raise_on_error=True):
if args is None:
args = ''
if all:
args += 'A'
if verbose:
args += 'f'
if len(args) > 0 and args[0] != '-':
args = '-' + args
results = self.wait(('ps %s %s' % (args, options)).strip(),
raise_on_error=raise_on_error)
if as_frame == 'auto':
as_frame = has_pandas
if as_frame:
if not has_pandas:
raise ImportError("Unable to import pandas")
df = pd.read_fwf(StringIO(results))
cmd_loc = df.columns.get_loc('CMD')
if cmd_loc < len(df.columns):
col = cmd_loc.fillna('')
for i in range(cmd_loc + 1, len(df.columns)):
col = col + df.icol(i).fillna('')
df['CMD'] = col
return df
return results
def top(self):
return self.ps('o', TOP_OPTIONS)
def git(self, username, repo, alias=None, token=None):
"""
Parameters
----------
token: str, default None
Assumes you have GITHUB_TOKEN in envvar if None
https://github.com/blog/1270-easier-builds-and-deployments-using-git-
over-https-and-oauth
"""
if alias is None:
alias = repo
if token is None:
token = os.environ.get('GITHUB_TOKEN')
self.wait('mkdir -p %s' % alias)
old_dir = self.pwd
try:
self.chdir(alias, relative=True)
cmd = 'git init && git pull https://%s@github.com/%s/%s.git'
# last line to stderr
return self.wait(cmd % (token, username, repo),
raise_on_error=False)
finally:
self.chdir(old_dir, relative=False)
TOP_OPTIONS = '%cpu,%mem,user,comm' | 0.593963 | 0.079961 |
import argparse
import pandas as pd
from password_analyse import PasswordAnalyse
from generate_password import GeneratePassword
DATA_PATH = 'data/'
WORD_LIST_PATH = 'data/wordlist.txt'
KEY_LIST_PATH = 'data/keylist.txt'
TRAIN_DATA_PATH = 'data/12306.csv'
PATTERN_FILE = 'result/pattern.txt'
PATTERN_PATH = 'result/'
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--count", help="Number of password", type=int)
parser.add_argument("-n", "--name", help="Input name")
parser.add_argument("-b", "--birthday", help="Input Birthday")
parser.add_argument("-e", "--email", help="Input Email")
parser.add_argument("-i", "--idcard", help="Input ID card")
parser.add_argument("-a", "--account", help="Input Account")
parser.add_argument("-g", "--generate", help="No information", action='store_true')
parser.add_argument("-t", "--train", help="Train your own model", action='store_true')
parser.add_argument("--analyse", help="Analyse your own data")
args = parser.parse_args()
count = args.count
pattern_file = open(PATTERN_FILE, 'r')
pattern_set = pattern_file.readlines()
gen = GeneratePassword(PATTERN_PATH, pattern_set)
# User give info
if args.name and args.birthday and args.email and args.idcard and args.account:
info = {
'name': args.name,
'birthday': args.birthday,
'email': args.email,
'id_card': args.idcard,
'account_name': args.account
}
if count:
result = gen.generate_info(info, count)
else:
result = gen.generate_info(info)
gen.save_result(result)
gen.show_result(result)
elif args.generate:
if count:
result = gen.generate_no_info(count)
else:
result = gen.generate_no_info()
gen.save_result(result)
gen.show_result(result)
elif args.train:
# read data
data = pd.read_csv(TRAIN_DATA_PATH, encoding='utf-8')
password = data['password'].values
email = data['email'].values
name = data['name'].values
id_card = data['id_card'].values
account_name = data['account_name'].values
phone_num = data['phone_num'].values
info_set = {
'password': password,
'email': email,
'name': name,
'id_card': id_card,
'account_name': account_name,
}
# read wordlist
word_list = open(WORD_LIST_PATH, 'r').readlines()
key_list = open(KEY_LIST_PATH, 'r').readlines()
print('=== Train Start ===\n')
ana = PasswordAnalyse('/result_test', info_set, word_list, key_list)
ana.analyse_total()
print('=== Train Finish ===\n')
elif args.analyse:
print("-- To be Continued. --\n")
print("-- Maybe there will be an Edition-3. Who knows. --\n")
analyse_content = args.analyse
if analyse_content == 'word':
pass
elif analyse_content == 'keyboard':
pass
elif analyse_content == 'structure':
pass
elif analyse_content == 'special':
pass
elif analyse_content == 'date':
pass
elif analyse_content =='cd_attack':
pass
pass
else:
print("Oops! Failed to deal with the parameter. Please input again.\n") | main.py | import argparse
import pandas as pd
from password_analyse import PasswordAnalyse
from generate_password import GeneratePassword
DATA_PATH = 'data/'
WORD_LIST_PATH = 'data/wordlist.txt'
KEY_LIST_PATH = 'data/keylist.txt'
TRAIN_DATA_PATH = 'data/12306.csv'
PATTERN_FILE = 'result/pattern.txt'
PATTERN_PATH = 'result/'
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--count", help="Number of password", type=int)
parser.add_argument("-n", "--name", help="Input name")
parser.add_argument("-b", "--birthday", help="Input Birthday")
parser.add_argument("-e", "--email", help="Input Email")
parser.add_argument("-i", "--idcard", help="Input ID card")
parser.add_argument("-a", "--account", help="Input Account")
parser.add_argument("-g", "--generate", help="No information", action='store_true')
parser.add_argument("-t", "--train", help="Train your own model", action='store_true')
parser.add_argument("--analyse", help="Analyse your own data")
args = parser.parse_args()
count = args.count
pattern_file = open(PATTERN_FILE, 'r')
pattern_set = pattern_file.readlines()
gen = GeneratePassword(PATTERN_PATH, pattern_set)
# User give info
if args.name and args.birthday and args.email and args.idcard and args.account:
info = {
'name': args.name,
'birthday': args.birthday,
'email': args.email,
'id_card': args.idcard,
'account_name': args.account
}
if count:
result = gen.generate_info(info, count)
else:
result = gen.generate_info(info)
gen.save_result(result)
gen.show_result(result)
elif args.generate:
if count:
result = gen.generate_no_info(count)
else:
result = gen.generate_no_info()
gen.save_result(result)
gen.show_result(result)
elif args.train:
# read data
data = pd.read_csv(TRAIN_DATA_PATH, encoding='utf-8')
password = data['password'].values
email = data['email'].values
name = data['name'].values
id_card = data['id_card'].values
account_name = data['account_name'].values
phone_num = data['phone_num'].values
info_set = {
'password': password,
'email': email,
'name': name,
'id_card': id_card,
'account_name': account_name,
}
# read wordlist
word_list = open(WORD_LIST_PATH, 'r').readlines()
key_list = open(KEY_LIST_PATH, 'r').readlines()
print('=== Train Start ===\n')
ana = PasswordAnalyse('/result_test', info_set, word_list, key_list)
ana.analyse_total()
print('=== Train Finish ===\n')
elif args.analyse:
print("-- To be Continued. --\n")
print("-- Maybe there will be an Edition-3. Who knows. --\n")
analyse_content = args.analyse
if analyse_content == 'word':
pass
elif analyse_content == 'keyboard':
pass
elif analyse_content == 'structure':
pass
elif analyse_content == 'special':
pass
elif analyse_content == 'date':
pass
elif analyse_content =='cd_attack':
pass
pass
else:
print("Oops! Failed to deal with the parameter. Please input again.\n") | 0.111241 | 0.06236 |
from app import socketio
from config import *
from .spi import *
from ..socketio_queue import EmitQueue
from flask_socketio import Namespace
import logging
logger = logging.getLogger("SIO_Server")
class XApiNamespace(Namespace):
md = None
td = None
mq = None
spi = None
orders_map = {}
def __init__(self, namespace=None):
super(XApiNamespace, self).__init__(namespace)
self.mq = EmitQueue(socketio)
self.spi = md_spi(self.mq, self.namespace)
def start(self):
# 有客户端连接上来时才启动
# 1. 网页已经连接过一没有关,重开服务端也会导致触发
# 2. 服务端已经连接成功了,但没有通知
if self.md is None:
self.md = config_md()
if enable_md:
init_md(self.md)
if self.td is None:
self.td = config_td()
init_td(self.td)
def stop(self):
if self.md is not None:
self.md.disconnect()
self.md = None
if self.td is not None:
self.td.disconnect()
self.td = None
def connect(self):
self.spi.set_api(self.md, self.td)
self.md.register_spi(self.spi)
if not self.md.is_connected():
if enable_md:
self.md.connect()
self.td.register_spi(self.spi)
if not self.td.is_connected():
if enable_td:
self.td.connect()
def on_connect(self):
# 刷新网页时这里会触发两次,所以需要做到防止重连
logger.info('on_connect')
self.start()
self.connect()
self.spi.emit_is_connected()
def on_disconnect(self):
# 得所有连接都断开才能取消订阅行情
logger.info('on_disconnect')
def on_sub_quote(self, data):
logger.info('on_sub_quote:%s', data)
args = data['args']
if not self.md.is_connected():
return
self.md.subscribe(args['instruments'], args['exchange'])
def on_unsub_quote(self, data):
logger.info('on_unsub_quote:%s', data)
args = data['args']
if not self.md.is_connected():
return
self.md.unsubscribe(args['instruments'], args['exchange'])
def on_send_order(self, data):
logger.info('on_send_order:%s', data)
args = data['args']
if not self.td.is_connected():
return
# 默认数据,如果输入的参数不够全,使用默认参数
_d0 = {
"InstrumentID": "c1909",
"Type": "Limit",
"Side": "Buy",
"Qty": 1,
"Price": 100.0,
"OpenClose": "Open",
"HedgeFlag": "Speculation",
}
_input = args
# 使用输出的参数更新默认字典,防止下面取枚举时出错
_d0.update(_input)
# 将原订单中的枚举字符串都换成数字
_d1 = {
'Type': OrderType[_d0["Type"]],
'Side': OrderSide[_d0["Side"]],
'OpenClose': OpenCloseType[_d0["OpenClose"]],
'HedgeFlag': HedgeFlagType[_d0["HedgeFlag"]],
}
_d0.update(_d1)
local_id = _d0['LocalID']
order_id = self.td.send_order(_d0)
# 也可以不设置,但这样远程就无法关联了
if len(local_id) > 0:
self.orders_map[order_id] = local_id
def on_cancel_order(self, data):
logger.info('on_cancel_order:%s', data)
args = data['args']
if not self.td.is_connected():
return
self.td.cancel_order(args["ID"])
def on_query_account(self, data):
logger.info('on_query_account')
query = ReqQueryField()
self.td.req_query(QueryType.ReqQryTradingAccount, query)
def on_query_positions(self, data):
logger.info('on_query_positions')
query = ReqQueryField()
self.td.req_query(QueryType.ReqQryInvestorPosition, query)
def on_query_instrument(self, data):
logger.info('on_query_instrument')
args = data['args']
query = ReqQueryField()
try:
exchange_id = args['ExchangeID']
query.ExchangeID = exchange_id.encode()
except:
pass
self.td.req_query(QueryType.ReqQryInstrument, query)
def on_query_order(self, data):
logger.info('on_query_order')
args = data['args']
query = ReqQueryField()
self.td.req_query(QueryType.ReqQryOrder, query)
def on_query_settlement_info(self, data):
logger.info('on_query_settlement_info:%s', data)
args = data['args']
query = ReqQueryField()
query.DateStart = args["TradingDay"]
self.td.req_query(QueryType.ReqQrySettlementInfo, query)
def on_query_history_data(self, data):
logger.info('on_query_history_data:%s', data)
args = data['args']
self.spi.emit_rsp_qry_history_data(args) | languages/Server/app/api/events.py | from app import socketio
from config import *
from .spi import *
from ..socketio_queue import EmitQueue
from flask_socketio import Namespace
import logging
logger = logging.getLogger("SIO_Server")
class XApiNamespace(Namespace):
md = None
td = None
mq = None
spi = None
orders_map = {}
def __init__(self, namespace=None):
super(XApiNamespace, self).__init__(namespace)
self.mq = EmitQueue(socketio)
self.spi = md_spi(self.mq, self.namespace)
def start(self):
# 有客户端连接上来时才启动
# 1. 网页已经连接过一没有关,重开服务端也会导致触发
# 2. 服务端已经连接成功了,但没有通知
if self.md is None:
self.md = config_md()
if enable_md:
init_md(self.md)
if self.td is None:
self.td = config_td()
init_td(self.td)
def stop(self):
if self.md is not None:
self.md.disconnect()
self.md = None
if self.td is not None:
self.td.disconnect()
self.td = None
def connect(self):
self.spi.set_api(self.md, self.td)
self.md.register_spi(self.spi)
if not self.md.is_connected():
if enable_md:
self.md.connect()
self.td.register_spi(self.spi)
if not self.td.is_connected():
if enable_td:
self.td.connect()
def on_connect(self):
# 刷新网页时这里会触发两次,所以需要做到防止重连
logger.info('on_connect')
self.start()
self.connect()
self.spi.emit_is_connected()
def on_disconnect(self):
# 得所有连接都断开才能取消订阅行情
logger.info('on_disconnect')
def on_sub_quote(self, data):
logger.info('on_sub_quote:%s', data)
args = data['args']
if not self.md.is_connected():
return
self.md.subscribe(args['instruments'], args['exchange'])
def on_unsub_quote(self, data):
logger.info('on_unsub_quote:%s', data)
args = data['args']
if not self.md.is_connected():
return
self.md.unsubscribe(args['instruments'], args['exchange'])
def on_send_order(self, data):
logger.info('on_send_order:%s', data)
args = data['args']
if not self.td.is_connected():
return
# 默认数据,如果输入的参数不够全,使用默认参数
_d0 = {
"InstrumentID": "c1909",
"Type": "Limit",
"Side": "Buy",
"Qty": 1,
"Price": 100.0,
"OpenClose": "Open",
"HedgeFlag": "Speculation",
}
_input = args
# 使用输出的参数更新默认字典,防止下面取枚举时出错
_d0.update(_input)
# 将原订单中的枚举字符串都换成数字
_d1 = {
'Type': OrderType[_d0["Type"]],
'Side': OrderSide[_d0["Side"]],
'OpenClose': OpenCloseType[_d0["OpenClose"]],
'HedgeFlag': HedgeFlagType[_d0["HedgeFlag"]],
}
_d0.update(_d1)
local_id = _d0['LocalID']
order_id = self.td.send_order(_d0)
# 也可以不设置,但这样远程就无法关联了
if len(local_id) > 0:
self.orders_map[order_id] = local_id
def on_cancel_order(self, data):
logger.info('on_cancel_order:%s', data)
args = data['args']
if not self.td.is_connected():
return
self.td.cancel_order(args["ID"])
def on_query_account(self, data):
logger.info('on_query_account')
query = ReqQueryField()
self.td.req_query(QueryType.ReqQryTradingAccount, query)
def on_query_positions(self, data):
logger.info('on_query_positions')
query = ReqQueryField()
self.td.req_query(QueryType.ReqQryInvestorPosition, query)
def on_query_instrument(self, data):
logger.info('on_query_instrument')
args = data['args']
query = ReqQueryField()
try:
exchange_id = args['ExchangeID']
query.ExchangeID = exchange_id.encode()
except:
pass
self.td.req_query(QueryType.ReqQryInstrument, query)
def on_query_order(self, data):
logger.info('on_query_order')
args = data['args']
query = ReqQueryField()
self.td.req_query(QueryType.ReqQryOrder, query)
def on_query_settlement_info(self, data):
logger.info('on_query_settlement_info:%s', data)
args = data['args']
query = ReqQueryField()
query.DateStart = args["TradingDay"]
self.td.req_query(QueryType.ReqQrySettlementInfo, query)
def on_query_history_data(self, data):
logger.info('on_query_history_data:%s', data)
args = data['args']
self.spi.emit_rsp_qry_history_data(args) | 0.270769 | 0.167151 |
import spotipy.util as util
from progress.bar import Bar
import numpy as np
from bs4 import BeautifulSoup
import pandas as pd
from wordcloud import WordCloud, STOPWORDS
import json, requests, urllib.parse, re, time, sys, click, spotipy, os
def auth():
username = 'default'
scope = 'user-read-private user-read-playback-state user-modify-playback-state user-library-read'
token = util.prompt_for_user_token(username,
scope,
client_id='', # CHANGE
client_secret='', # CHANGE
redirect_uri='http://localhost:8000/')
if token:
sp = spotipy.Spotify(auth=token)
# print('Authenticated')
return sp
else:
print("Failed to get token")
exit()
def get_lyric(artist, name, idx):
try:
query = urllib.parse.quote_plus(artist + ' ' + name)
# print(idx, query)
url = "https://genius.com/api/search/multi?per_page=5&q=" + query
response = requests.get(url)
result = json.loads(response.text)
try:
for i in result['response']['sections']:
if i['type'] == 'song':
lyric_url = i['hits'][0]['result']['url']
except:
return np.NaN
lyric_response = requests.get(lyric_url)
soup = BeautifulSoup(lyric_response.content, 'html.parser')
lyric_divs = soup.find_all('div', class_='lyrics')
lyrics = ''
if lyric_divs:
for i in lyric_divs:
lyrics += i.text.replace('\n', ' ').replace('"', "' ")
else:
lyrics += soup.find('div', class_='Lyrics__Container-sc-1ynbvzw-2 jgQsqn').getText(separator=" ").replace('"', "' ")
rules = [r'\[.*?\]', r'\(.*?\)', r'[?,.]']
for rule in rules:
lyrics = re.sub(rule, '', lyrics)
# lyrics = re.sub(r'la.', '', lyrics)
# lyrics = re.sub(r'[ \t]{2,}', '', lyrics)
return lyrics
except:
return -1
def generate_lyrics(URI):
sp = auth()
df = pd.DataFrame(columns=['uri', 'name', 'artist', 'lyrics'])
data = []
try:
results = sp.playlist_items(URI)
for t in results['items']:
data.append({'uri': t['track']['uri'], 'name': t['track']['name'], 'artist': t['track']['artists'][0]['name']})
except spotipy.exceptions.SpotifyException:
print('The URI does not exist')
exit()
while results['next']:
results = sp.next(results)
for t in results['items']:
data.append({'uri': t['track']['uri'], 'name': t['track']['name'], 'artist': t['track']['artists'][0]['name']})
df = df.append(data, ignore_index=True)
bar = Bar('Getting Lyrics', max=len(df))
for idx, row in df.iterrows():
for attempt in range(10):
lyrics = get_lyric(row['artist'], row['name'], idx)
if lyrics != -1:
row['lyrics'] = lyrics
break
else:
print('sleeping', attempt)
time.sleep(5)
bar.next()
bar.finish()
print('Could not find lyrics for: {} songs'.format(df['lyrics'].isna().sum()))
df = df.dropna()
df.to_csv(URI[-22:] + '_lyrics.csv', index=False)
print("Saved lyrics to file")
def create_database(URI):
print("Gettng songs this may take a while...")
generate_lyrics(URI)
def run_blender(URI):
if click.confirm("Do you want to run the blender file now?", default=True):
os.system("blender -b -P WordPile.py -- " + URI)
return None
def generate_freq(URI):
df = pd.read_csv(URI[-22:] + '_lyrics.csv')
all_words = []
for i in df['lyrics'].values:
all_words += str(i).lower().split()
word_freq = WordCloud().process_text(' '.join(all_words))
with open(URI[-22:] + '.txt', 'w') as f:
json.dump(word_freq, f)
print("Saved frequencies to " + URI[-22:] + '.txt')
run_blender(URI)
def look_for_lyrics(URI):
try:
open(URI[-22:] + '_lyrics.csv')
return -1
except IOError:
print("New Playlist...")
return
def validate_uri(URI_maybe):
URI = re.findall(r"spotify:playlist:[A-Za-z0-9]{22}", URI_maybe)
if URI:
return URI[0]
else:
print("Not a valid URI")
exit()
def main():
argv = sys.argv
if len(argv) > 1:
URI_maybe = argv[1]
print('\n' + URI_maybe)
URI = validate_uri(URI_maybe)
response = look_for_lyrics(URI)
if response == -1:
if click.confirm("You have alread created a lyrics file, create another?", default=True):
create_database(URI)
generate_freq(URI)
else:
generate_freq(URI)
else:
print("Creating a new database...")
create_database(URI)
generate_freq(URI)
else:
print("Usage: python generat_freq.py <URI>")
if __name__ == "__main__":
main()
# command = 'blender -b --python WordPile.py <URI>' | generate_freq.py | import spotipy.util as util
from progress.bar import Bar
import numpy as np
from bs4 import BeautifulSoup
import pandas as pd
from wordcloud import WordCloud, STOPWORDS
import json, requests, urllib.parse, re, time, sys, click, spotipy, os
def auth():
username = 'default'
scope = 'user-read-private user-read-playback-state user-modify-playback-state user-library-read'
token = util.prompt_for_user_token(username,
scope,
client_id='', # CHANGE
client_secret='', # CHANGE
redirect_uri='http://localhost:8000/')
if token:
sp = spotipy.Spotify(auth=token)
# print('Authenticated')
return sp
else:
print("Failed to get token")
exit()
def get_lyric(artist, name, idx):
try:
query = urllib.parse.quote_plus(artist + ' ' + name)
# print(idx, query)
url = "https://genius.com/api/search/multi?per_page=5&q=" + query
response = requests.get(url)
result = json.loads(response.text)
try:
for i in result['response']['sections']:
if i['type'] == 'song':
lyric_url = i['hits'][0]['result']['url']
except:
return np.NaN
lyric_response = requests.get(lyric_url)
soup = BeautifulSoup(lyric_response.content, 'html.parser')
lyric_divs = soup.find_all('div', class_='lyrics')
lyrics = ''
if lyric_divs:
for i in lyric_divs:
lyrics += i.text.replace('\n', ' ').replace('"', "' ")
else:
lyrics += soup.find('div', class_='Lyrics__Container-sc-1ynbvzw-2 jgQsqn').getText(separator=" ").replace('"', "' ")
rules = [r'\[.*?\]', r'\(.*?\)', r'[?,.]']
for rule in rules:
lyrics = re.sub(rule, '', lyrics)
# lyrics = re.sub(r'la.', '', lyrics)
# lyrics = re.sub(r'[ \t]{2,}', '', lyrics)
return lyrics
except:
return -1
def generate_lyrics(URI):
sp = auth()
df = pd.DataFrame(columns=['uri', 'name', 'artist', 'lyrics'])
data = []
try:
results = sp.playlist_items(URI)
for t in results['items']:
data.append({'uri': t['track']['uri'], 'name': t['track']['name'], 'artist': t['track']['artists'][0]['name']})
except spotipy.exceptions.SpotifyException:
print('The URI does not exist')
exit()
while results['next']:
results = sp.next(results)
for t in results['items']:
data.append({'uri': t['track']['uri'], 'name': t['track']['name'], 'artist': t['track']['artists'][0]['name']})
df = df.append(data, ignore_index=True)
bar = Bar('Getting Lyrics', max=len(df))
for idx, row in df.iterrows():
for attempt in range(10):
lyrics = get_lyric(row['artist'], row['name'], idx)
if lyrics != -1:
row['lyrics'] = lyrics
break
else:
print('sleeping', attempt)
time.sleep(5)
bar.next()
bar.finish()
print('Could not find lyrics for: {} songs'.format(df['lyrics'].isna().sum()))
df = df.dropna()
df.to_csv(URI[-22:] + '_lyrics.csv', index=False)
print("Saved lyrics to file")
def create_database(URI):
print("Gettng songs this may take a while...")
generate_lyrics(URI)
def run_blender(URI):
if click.confirm("Do you want to run the blender file now?", default=True):
os.system("blender -b -P WordPile.py -- " + URI)
return None
def generate_freq(URI):
df = pd.read_csv(URI[-22:] + '_lyrics.csv')
all_words = []
for i in df['lyrics'].values:
all_words += str(i).lower().split()
word_freq = WordCloud().process_text(' '.join(all_words))
with open(URI[-22:] + '.txt', 'w') as f:
json.dump(word_freq, f)
print("Saved frequencies to " + URI[-22:] + '.txt')
run_blender(URI)
def look_for_lyrics(URI):
try:
open(URI[-22:] + '_lyrics.csv')
return -1
except IOError:
print("New Playlist...")
return
def validate_uri(URI_maybe):
URI = re.findall(r"spotify:playlist:[A-Za-z0-9]{22}", URI_maybe)
if URI:
return URI[0]
else:
print("Not a valid URI")
exit()
def main():
argv = sys.argv
if len(argv) > 1:
URI_maybe = argv[1]
print('\n' + URI_maybe)
URI = validate_uri(URI_maybe)
response = look_for_lyrics(URI)
if response == -1:
if click.confirm("You have alread created a lyrics file, create another?", default=True):
create_database(URI)
generate_freq(URI)
else:
generate_freq(URI)
else:
print("Creating a new database...")
create_database(URI)
generate_freq(URI)
else:
print("Usage: python generat_freq.py <URI>")
if __name__ == "__main__":
main()
# command = 'blender -b --python WordPile.py <URI>' | 0.12692 | 0.080719 |
import os
import h5py, torch
import numpy as np
import keras
from numpy.random import seed as numpy_seed
from tensorflow import set_random_seed
from keras.engine.saving import load_attributes_from_hdf5_group
def initialize_with_keras_hdf5(keras_model, dict_map, torch_model,
model_path=None, seed=None):
"""
:param keras_model: a keras model created by keras.models.Sequential
:param dict_map: a dictionary maps keys from Kera => PyTorch
:param torch_model: a PyTorch network
:param model_path: path where h5 file located, if None, than keras will initialize a new network
:return: PyTorch StateDict
"""
if model_path:
weight_dict = load_weights_from_hdf5(model_path, keras_model)
else:
if seed:
numpy_seed(seed)
set_random_seed(seed)
keras_model.compile(keras.optimizers.adam())
weight_dict = {}
for layer in keras_model.layers:
weight_dict.update({layer.name: layer.get_weights()})
state_dict = torch_model.state_dict()
for key in weight_dict.keys():
destiny = dict_map[key]
for i, item in enumerate(destiny):
if len(weight_dict[key][i].shape) == 4:
# Convolutional Layer
tensor = np.transpose(weight_dict[key][i], (3, 2, 0, 1))
elif len(weight_dict[key][i].shape) == 2:
# Full Connection Layer
tensor = np.transpose(weight_dict[key][i], (1, 0))
else:
tensor = weight_dict[key][i]
state_dict[item] = torch.tensor(tensor)
torch_model.load_state_dict(state_dict)
return torch_model
def load_weights_from_hdf5(model_path, keras_model):
f = h5py.File(model_path, 'r')['model_weights']
layers = keras_model.inner_model.layers if hasattr(keras_model, "inner_model") \
else keras_model.layers
filtered_layers = []
for layer in layers:
weights = layer.weights
if weights:
filtered_layers.append(layer)
layer_names = load_attributes_from_hdf5_group(f, 'layer_names')
filtered_layer_names = []
for name in layer_names:
g = f[name]
weight_names = load_attributes_from_hdf5_group(g, 'weight_names')
if weight_names:
filtered_layer_names.append(name)
layer_names = filtered_layer_names
if len(layer_names) != len(filtered_layers):
raise ValueError('You are trying to load a weight file '
'containing ' + str(len(layer_names)) +
' layers into a model with ' +
str(len(filtered_layers)) + ' layers.')
weight_dict = {}
for k, name in enumerate(layer_names):
g = f[name]
weight_names = load_attributes_from_hdf5_group(g, 'weight_names')
weight_values = [np.asarray(g[weight_name]) for weight_name in weight_names]
weight_dict.update({name: weight_values})
return weight_dict
if __name__ == "__main__":
from keras.models import Sequential
from keras.layers import *
model_path = os.path.join(os.getcwd(), 'models', "cifar10_cnn.h5")
model = Sequential()
model.add(Conv2D(32, 3, padding='same', input_shape=(32, 32, 3), activation='relu'))
model.add(Conv2D(32, 3, activation='relu'))
model.add(MaxPooling2D())
model.add(Dropout(0.25))
model.add(Conv2D(64, 3, padding='same', activation='relu'))
model.add(Conv2D(64, 3, activation='relu'))
model.add(MaxPooling2D())
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(10))
model.add(Activation('softmax'))
weight_dict = load_weights_from_hdf5(model_path, model)
print(weight_dict) | utils/weight_transfer.py | import os
import h5py, torch
import numpy as np
import keras
from numpy.random import seed as numpy_seed
from tensorflow import set_random_seed
from keras.engine.saving import load_attributes_from_hdf5_group
def initialize_with_keras_hdf5(keras_model, dict_map, torch_model,
model_path=None, seed=None):
"""
:param keras_model: a keras model created by keras.models.Sequential
:param dict_map: a dictionary maps keys from Kera => PyTorch
:param torch_model: a PyTorch network
:param model_path: path where h5 file located, if None, than keras will initialize a new network
:return: PyTorch StateDict
"""
if model_path:
weight_dict = load_weights_from_hdf5(model_path, keras_model)
else:
if seed:
numpy_seed(seed)
set_random_seed(seed)
keras_model.compile(keras.optimizers.adam())
weight_dict = {}
for layer in keras_model.layers:
weight_dict.update({layer.name: layer.get_weights()})
state_dict = torch_model.state_dict()
for key in weight_dict.keys():
destiny = dict_map[key]
for i, item in enumerate(destiny):
if len(weight_dict[key][i].shape) == 4:
# Convolutional Layer
tensor = np.transpose(weight_dict[key][i], (3, 2, 0, 1))
elif len(weight_dict[key][i].shape) == 2:
# Full Connection Layer
tensor = np.transpose(weight_dict[key][i], (1, 0))
else:
tensor = weight_dict[key][i]
state_dict[item] = torch.tensor(tensor)
torch_model.load_state_dict(state_dict)
return torch_model
def load_weights_from_hdf5(model_path, keras_model):
f = h5py.File(model_path, 'r')['model_weights']
layers = keras_model.inner_model.layers if hasattr(keras_model, "inner_model") \
else keras_model.layers
filtered_layers = []
for layer in layers:
weights = layer.weights
if weights:
filtered_layers.append(layer)
layer_names = load_attributes_from_hdf5_group(f, 'layer_names')
filtered_layer_names = []
for name in layer_names:
g = f[name]
weight_names = load_attributes_from_hdf5_group(g, 'weight_names')
if weight_names:
filtered_layer_names.append(name)
layer_names = filtered_layer_names
if len(layer_names) != len(filtered_layers):
raise ValueError('You are trying to load a weight file '
'containing ' + str(len(layer_names)) +
' layers into a model with ' +
str(len(filtered_layers)) + ' layers.')
weight_dict = {}
for k, name in enumerate(layer_names):
g = f[name]
weight_names = load_attributes_from_hdf5_group(g, 'weight_names')
weight_values = [np.asarray(g[weight_name]) for weight_name in weight_names]
weight_dict.update({name: weight_values})
return weight_dict
if __name__ == "__main__":
from keras.models import Sequential
from keras.layers import *
model_path = os.path.join(os.getcwd(), 'models', "cifar10_cnn.h5")
model = Sequential()
model.add(Conv2D(32, 3, padding='same', input_shape=(32, 32, 3), activation='relu'))
model.add(Conv2D(32, 3, activation='relu'))
model.add(MaxPooling2D())
model.add(Dropout(0.25))
model.add(Conv2D(64, 3, padding='same', activation='relu'))
model.add(Conv2D(64, 3, activation='relu'))
model.add(MaxPooling2D())
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(10))
model.add(Activation('softmax'))
weight_dict = load_weights_from_hdf5(model_path, model)
print(weight_dict) | 0.7917 | 0.366873 |
from typing import Iterable, Mapping, Union, Optional, Tuple
import pathlib
import json
from abc import abstractmethod
from enum import Enum, auto
import torch
from torch import nn
from .codemaps_helpers import (CodemapsHelper,
SimpleCodemapsHelper, ZigZagCodemapsHelper)
from VQCPCB.transformer.transformer_custom import (
TransformerCustom, TransformerDecoderCustom, TransformerEncoderCustom,
TransformerDecoderLayerCustom, TransformerEncoderLayerCustom,
TransformerAlignedDecoderLayerCustom)
class Seq2SeqInputKind(Enum):
"""Types of input sequences for seq2seq models"""
Source = auto()
Target = auto()
class VQNSynthTransformer(nn.Module):
"""Transformer-based generative model for latent maps
Inputs are expected to be of shape [num_frequency_bands, time_duration],
with `sample[0, 0]` in the image the energy in the lowest frequency band
in the first time-frame.
Arguments:
* predict_frequencies_first (bool, optional, default is False):
if True, transposes the inputs to predict time-frame by time-frame,
potentially bringing more coherence in frequency within a given
time-frame by bringing the dependencies closer.
* predict_low_frequencies_first (bool, optional, default is True):
if False, flips the inputs so that frequencies are predicted in
decreasing order, starting at the harmonics.
* class_conditioning_num_classes_per_modality (iterable of int,
optional, default is None):
when using class-labels for conditioning, provide in this iterable
the number of classes per modality (e.g. pitch, instrument class...)
to intialize the embeddings layer
* class_conditioning_embedding_dim_per_modality (iterable of int,
optional, default is None):
when using class-labels for conditioning, provide in this iterable the
dimension of embeddings to use for each modality
"""
# helper attributes for appropriately flattening codemaps to sequences
source_codemaps_helper: SimpleCodemapsHelper
target_codemaps_helper: CodemapsHelper
@property
@abstractmethod
def use_inpainting_mask_on_source(self) -> bool:
"""Whether to introduce a specific masking token for the source sequences
This masking token is used to simulate partial information for
inpaiting operations.
"""
...
def __init__(
self,
shape: Iterable[int], # [num_frequencies, frame_duration]
n_class: int,
channel: int,
kernel_size: int,
n_block: int,
n_res_block: int,
res_channel: int,
attention: bool = True, # TODO: remove this parameter
dropout: float = 0.1,
n_cond_res_block: int = 0,
cond_res_channel: int = 0,
cond_res_kernel: int = 3,
n_out_res_block: int = 0,
predict_frequencies_first: bool = False,
predict_low_frequencies_first: bool = True,
d_model: int = 512,
embeddings_dim: int = 32,
positional_embeddings_dim: int = 16,
use_relative_transformer: bool = False,
class_conditioning_num_classes_per_modality: Optional[Mapping[str, int]] = None,
class_conditioning_embedding_dim_per_modality: Optional[Mapping[str, int]] = None,
class_conditioning_prepend_to_dummy_input: bool = False,
local_class_conditioning: bool = False,
positional_class_conditioning: bool = False,
add_mask_token_to_symbols: bool = False,
conditional_model: bool = False,
self_conditional_model: bool = False,
use_aligned_decoder: bool = False,
condition_shape: Optional[Tuple[int, int]] = None,
conditional_model_num_encoder_layers: int = 6,
conditional_model_num_decoder_layers: int = 8,
conditional_model_nhead: int = 8,
unconditional_model_num_encoder_layers: int = 6,
unconditional_model_nhead: int = 8,
use_identity_memory_mask: bool = False,
use_lstm_DEBUG: bool = False,
disable_start_symbol_DEBUG: bool = False,
):
if local_class_conditioning:
raise NotImplementedError(
"Depecrated in favor of positional class conditioning")
self.shape = shape
if self_conditional_model:
assert use_relative_transformer, (
"Self conditioning only meanigful for relative transformers")
assert conditional_model, (
"Self-conditioning is a specific case of conditioning")
assert (condition_shape is None or condition_shape == shape)
assert not (local_class_conditioning and positional_class_conditioning)
self.conditional_model = conditional_model
if self.conditional_model:
assert condition_shape is not None
self.self_conditional_model = self_conditional_model
self.use_relative_transformer = use_relative_transformer
if self.use_relative_transformer and not predict_frequencies_first:
raise (NotImplementedError,
"Relative positioning only implemented along time")
self.condition_shape = condition_shape
if self.self_conditional_model:
self.condition_shape = self.shape.copy()
self.local_class_conditioning = local_class_conditioning
self.positional_class_conditioning = positional_class_conditioning
self.n_class = n_class
self.channel = channel
if kernel_size % 2 == 0:
self.kernel_size = kernel_size + 1
else:
self.kernel_size = kernel_size
self.n_block = n_block
self.n_res_block = n_res_block
self.res_channel = res_channel
self.dropout = dropout
self.n_cond_res_block = n_cond_res_block
self.cond_res_channel = cond_res_channel
self.cond_res_kernel = cond_res_kernel
self.n_out_res_block = n_out_res_block
self.predict_frequencies_first = predict_frequencies_first
self.predict_low_frequencies_first = predict_low_frequencies_first
self.d_model = d_model
self.embeddings_dim = embeddings_dim
# ensure an even value
self.positional_embeddings_dim = 2 * (positional_embeddings_dim // 2)
self.class_conditioning_num_classes_per_modality = class_conditioning_num_classes_per_modality
self.class_conditioning_embedding_dim_per_modality = class_conditioning_embedding_dim_per_modality
self.class_conditioning_prepend_to_dummy_input = class_conditioning_prepend_to_dummy_input
# TODO(theis) unify to self.num_encoder_layers and self.n_head
# and find a better way to manage the different default values
self.conditional_model_num_encoder_layers = conditional_model_num_encoder_layers
self.conditional_model_nhead = conditional_model_nhead
self.conditional_model_num_decoder_layers = conditional_model_num_decoder_layers
self.use_identity_memory_mask = use_identity_memory_mask
self.use_aligned_decoder = use_aligned_decoder
self.use_lstm_DEBUG = use_lstm_DEBUG
self.disable_start_symbol_DEBUG = disable_start_symbol_DEBUG
self._instantiation_parameters = self.__dict__.copy()
super().__init__()
if self.use_inpainting_mask_on_source:
# add one token to the available source sequence symbols
self.n_class_source = self.n_class + 1
self.mask_token_index = self.n_class_source - 1
# generated, target sequences cannot contain the masking token
self.n_class_target = self.n_class
else:
self.n_class_target = self.n_class_source = self.n_class
if self.class_conditioning_num_classes_per_modality is not None:
self.class_conditioning_num_modalities = len(
self.class_conditioning_embedding_dim_per_modality.values())
self.class_conditioning_total_dim = sum(
self.class_conditioning_embedding_dim_per_modality.values())
else:
self.class_conditioning_num_modalities = 0
self.class_conditioning_total_dim = 0
self.source_frequencies, self.source_duration = (
self.condition_shape)
self.source_num_channels, self.source_num_events = (
1, self.source_frequencies * self.source_duration)
self.source_transformer_sequence_length = (
self.source_frequencies * self.source_duration)
self.target_frequencies, self.target_duration = self.shape
self.target_transformer_sequence_length = (
self.target_frequencies * self.target_duration)
self.target_events_per_source_patch = (
(self.target_duration // self.source_duration)
* (self.target_frequencies // self.source_frequencies)
)
self.target_num_channels = (
self.target_events_per_source_patch)
self.target_num_events = (
self.target_transformer_sequence_length
// self.target_num_channels)
# downsampling_factor = (
# (self.shape[0]*self.shape[1])
# // (self.condition_shape[0]*self.condition_shape[1]))
# else:
# self.target_num_channels = self.source_num_channels
# self.target_num_events = self.source_num_events
self.output_sizes = (-1, self.target_frequencies,
self.target_duration,
self.n_class_target)
self.source_positional_embeddings_frequency = nn.Parameter(
torch.randn((1, # batch-size
self.source_frequencies, # frequency-dimension
1, # time-dimension
self.positional_embeddings_dim//2))
)
self.source_positional_embeddings_time = nn.Parameter(
torch.randn((1, # batch-size
1, # frequency-dimension
self.source_duration, # time-dimension
self.positional_embeddings_dim//2))
)
self.target_positional_embeddings_time = None
# decoder-level, patch-based relative position embeddings
# allows to locate elements within a patch of the decoder
self.target_positional_embeddings_patch = nn.Parameter(
torch.randn((1, # batch-size
self.target_frequencies // self.source_frequencies, # frequency-dimension
self.target_duration // self.source_duration, # time-dimension
self.positional_embeddings_dim // 2))
)
self.target_positional_embeddings_frequency = nn.Parameter(
torch.randn((1, # batch-size
self.target_frequencies, # frequency-dimension
1, # time-dimension
self.positional_embeddings_dim // 2))
)
if self.embeddings_dim is None:
self.embeddings_dim = self.d_model-self.positional_embeddings_dim
self.source_embed = torch.nn.Embedding(self.n_class_source,
self.embeddings_dim)
self.embeddings_effective_dim = (self.d_model
- self.positional_embeddings_dim)
if self.positional_class_conditioning:
self.embeddings_effective_dim -= self.class_conditioning_total_dim
self.source_embeddings_linear = nn.Linear(
self.embeddings_dim,
self.embeddings_effective_dim
)
self.target_embeddings_linear = nn.Linear(
self.embeddings_dim,
self.embeddings_effective_dim)
self.target_embed = torch.nn.Embedding(self.n_class_target,
self.embeddings_dim)
# convert Transformer outputs to class-probabilities (as logits)
self.project_transformer_outputs_to_logits = (
nn.Linear(self.d_model, self.n_class_target))
self.class_conditioning_embedding_layers = nn.ModuleDict()
self.class_conditioning_class_to_index_per_modality = {}
self.class_conditioning_start_positions_per_modality = {}
if self.class_conditioning_num_classes_per_modality is not None:
# initialize class conditioning embedding layers
for (modality_name, modality_num_classes), modality_embedding_dim in zip(
self.class_conditioning_num_classes_per_modality.items(),
self.class_conditioning_embedding_dim_per_modality.values()):
self.class_conditioning_embedding_layers[modality_name] = (
torch.nn.Embedding(modality_num_classes,
modality_embedding_dim)
)
# initialize start positions for class conditioning in start symbol
if self.positional_class_conditioning or self.class_conditioning_prepend_to_dummy_input:
# insert class conditioning at beginning of the start symbol
current_position = 0
for modality_name, modality_embedding_dim in (
self.class_conditioning_embedding_dim_per_modality.items()):
self.class_conditioning_start_positions_per_modality[modality_name] = (
current_position
)
current_position = current_position + modality_embedding_dim
else:
raise NotImplementedError
# insert class conditioning at end of the start symbol
current_position = self.d_model
for modality_name, modality_embedding_dim in (
self.class_conditioning_embedding_dim_per_modality.items()):
current_position = current_position - modality_embedding_dim
self.class_conditioning_start_positions_per_modality[modality_name] = (
current_position
)
self.class_conditioning_total_dim_with_positions = (
self.class_conditioning_total_dim
+ self.positional_embeddings_dim)
self.source_start_symbol_dim = self.d_model
if self.positional_class_conditioning:
self.source_start_symbol_dim -= self.class_conditioning_total_dim
# TODO reduce dimensionality of start symbol and use a linear layer to expand it
self.source_start_symbol = nn.Parameter(
torch.randn((1, 1, self.source_start_symbol_dim))
)
self.source_num_events_with_start_symbol = self.source_num_events + 1
self.source_transformer_sequence_length_with_start_symbol = (
self.source_transformer_sequence_length + 1
)
self.target_start_symbol_dim = self.d_model
if self.positional_class_conditioning:
self.target_start_symbol_dim -= self.class_conditioning_total_dim
target_start_symbol_duration = self.target_events_per_source_patch
self.target_start_symbol = nn.Parameter(
torch.randn((1, target_start_symbol_duration,
self.target_start_symbol_dim))
)
self.target_num_events_with_start_symbol = (
self.target_num_events + 1
)
self.target_transformer_sequence_length_with_start_symbol = (
self.target_num_events_with_start_symbol
* self.target_num_channels
)
self.transformer: Union[nn.Transformer, nn.TransformerEncoder,
TransformerCustom, TransformerEncoderCustom]
if self.use_lstm_DEBUG:
raise NotImplementedError(
"TODO(theis), debug mode with simple LSTM layers")
else:
encoder_nhead = self.conditional_model_nhead
encoder_num_layers = self.conditional_model_num_encoder_layers
encoder_layer = TransformerEncoderLayerCustom(
d_model=self.d_model,
nhead=encoder_nhead,
attention_bias_type='relative_attention',
num_channels=self.source_num_channels,
num_events=self.source_num_events_with_start_symbol
)
relative_encoder = TransformerEncoderCustom(
encoder_layer=encoder_layer,
num_layers=encoder_num_layers
)
attention_bias_type_cross = 'relative_attention_target_source'
if self.use_identity_memory_mask:
attention_bias_type_cross = 'no_bias'
decoder_layer_implementation: nn.Module
if self.use_aligned_decoder:
# hierarchical decoder, use an aligned implementation
# this computes cross-attention only with tokens from the source
# that directly condition underlying tokens in the target
decoder_layer_implementation = (
TransformerAlignedDecoderLayerCustom)
else:
decoder_layer_implementation = (
TransformerDecoderLayerCustom)
decoder_layer = decoder_layer_implementation(
d_model=self.d_model,
nhead=self.conditional_model_nhead,
attention_bias_type_self='relative_attention',
attention_bias_type_cross=attention_bias_type_cross,
num_channels_encoder=self.source_num_channels,
num_events_encoder=self.source_num_events_with_start_symbol,
num_channels_decoder=self.target_num_channels,
num_events_decoder=self.target_num_events_with_start_symbol
)
custom_decoder = TransformerDecoderCustom(
decoder_layer=decoder_layer,
num_layers=self.conditional_model_num_decoder_layers
)
self.transformer = TransformerCustom(
nhead=self.conditional_model_nhead,
custom_encoder=relative_encoder,
custom_decoder=custom_decoder,
d_model=self.d_model)
def embed_data(self, input: torch.Tensor, kind: Seq2SeqInputKind) -> torch.Tensor:
if kind == Seq2SeqInputKind.Source:
return self.source_embeddings_linear(self.source_embed(input))
elif kind == Seq2SeqInputKind.Target and self.conditional_model:
return self.target_embeddings_linear(self.target_embed(input))
else:
raise ValueError(f"Unexpected value {kind} for kind option")
def _get_combined_positional_embeddings(self, kind: Seq2SeqInputKind) -> torch.Tensor:
if kind == Seq2SeqInputKind.Source:
positional_embeddings_frequency = (
self.source_positional_embeddings_frequency)
positional_embeddings_time = self.source_positional_embeddings_time
frequencies = self.source_frequencies
duration = self.source_duration
elif kind == Seq2SeqInputKind.Target and self.conditional_model:
positional_embeddings_frequency = (
self.target_positional_embeddings_frequency)
positional_embeddings_time = self.target_positional_embeddings_time
frequencies = self.target_frequencies
duration = self.target_duration
else:
raise ValueError(f"Unexpected value {kind} for kind option")
batch_dim, frequency_dim, time_dim, embedding_dim = (0, 1, 2, 3)
repeated_frequency_embeddings = (
positional_embeddings_frequency
.repeat(1, 1, duration, 1))
if not self.use_relative_transformer:
repeated_time_embeddings = (
positional_embeddings_time
.repeat(1, frequencies, 1, 1))
return torch.cat([repeated_frequency_embeddings,
repeated_time_embeddings],
dim=embedding_dim)
else:
if kind == Seq2SeqInputKind.Target:
positional_embeddings_patch = (
self.target_positional_embeddings_patch)
repeated_patch_embeddings = (
positional_embeddings_patch
.repeat(
1, self.source_frequencies, self.source_duration, 1)
)
return torch.cat([repeated_frequency_embeddings,
repeated_patch_embeddings],
dim=embedding_dim)
else:
return torch.cat([repeated_frequency_embeddings,
repeated_frequency_embeddings],
dim=embedding_dim)
@property
def combined_positional_embeddings_source(self) -> torch.Tensor:
return self._get_combined_positional_embeddings(Seq2SeqInputKind.Source)
@property
def combined_positional_embeddings_target(self) -> torch.Tensor:
return self._get_combined_positional_embeddings(Seq2SeqInputKind.Target)
@property
def causal_mask(self) -> torch.Tensor:
"""Generate a mask to impose causality"""
if self.conditional_model:
# masking is applied only on the target, access is allowed to
# all positions on the conditioning input
causal_mask_length = (
self.target_transformer_sequence_length_with_start_symbol)
else:
# apply causal mask to the input for the prediction task
causal_mask_length = (
self.source_transformer_sequence_length_with_start_symbol)
mask = (torch.triu(torch.ones(causal_mask_length,
causal_mask_length)) == 1
).transpose(0, 1)
mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(
mask == 1, float(0.0))
return mask
@property
def identity_memory_mask(self) -> torch.Tensor:
identity_memory_mask = (
torch.eye(self.source_transformer_sequence_length_with_start_symbol).float())
identity_memory_mask = (
identity_memory_mask
.masked_fill(identity_memory_mask == 0, float('-inf'))
.masked_fill(identity_memory_mask == 1, float(0.0))
)
return identity_memory_mask
def to_sequences(self, input: torch.Tensor,
condition: Optional[torch.Tensor] = None,
class_conditioning: Mapping[str, torch.Tensor] = {},
mask: Optional[torch.BoolTensor] = None,
time_indexes_source: Optional[Iterable[int]] = None,
time_indexes_target: Optional[Iterable[int]] = None,
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
source_sequence = self.source_codemaps_helper.to_sequence(condition)
if mask is not None and self.use_inpainting_mask_on_source:
mask_sequence = self.source_codemaps_helper.to_sequence(mask)
else:
mask_sequence = None
source_sequence, _ = self.prepare_data(
source_sequence, kind=Seq2SeqInputKind.Source,
class_conditioning=class_conditioning,
mask=mask_sequence,
time_indexes=time_indexes_source)
target_sequence = self.target_codemaps_helper.to_sequence(input)
target_sequence, _ = self.prepare_data(
target_sequence, kind=Seq2SeqInputKind.Target,
class_conditioning=class_conditioning,
time_indexes=time_indexes_target)
return source_sequence, target_sequence
def prepare_data(self, sequence: torch.Tensor, kind: Seq2SeqInputKind,
class_conditioning: Mapping[str, torch.Tensor] = {},
mask: Optional[torch.Tensor] = None,
time_indexes: Optional[Iterable[int]] = None
) -> torch.Tensor:
if mask is not None:
sequence = sequence.masked_fill(mask, self.mask_token_index)
(batch_dim, sequence_dim, embedding_dim) = (0, 1, 2)
embedded_sequence = self.embed_data(sequence, kind=kind)
embedded_sequence_with_positions = self.add_positions_to_sequence(
embedded_sequence, kind=kind, embedding_dim=embedding_dim,
time_indexes=time_indexes
)
if self.positional_class_conditioning:
embedded_sequence_with_positions = (
self.add_class_conditioning_to_sequence(
embedded_sequence_with_positions,
class_conditioning)
)
prepared_sequence = self.add_start_symbol(
embedded_sequence_with_positions, kind=kind,
class_conditioning=class_conditioning, sequence_dim=1
)
frequency_dim, time_dim = (2, 1)
return prepared_sequence, (
(batch_dim, frequency_dim, time_dim))
def add_positions_to_sequence(self, sequence: torch.Tensor,
kind: Seq2SeqInputKind,
embedding_dim: int,
time_indexes: Optional[Iterable[int]]):
# add positional embeddings
batch_size = sequence.shape[0]
# combine time and frequency embeddings
if kind == Seq2SeqInputKind.Source:
frequencies = self.source_frequencies
duration = self.source_duration
positional_embeddings = self.combined_positional_embeddings_source
transformer_sequence_length = (
self.source_transformer_sequence_length)
elif kind == Seq2SeqInputKind.Target:
frequencies = self.target_frequencies
duration = self.target_duration
positional_embeddings = self.combined_positional_embeddings_target
transformer_sequence_length = (
self.target_transformer_sequence_length)
else:
raise ValueError(f"Unexpected value {kind} for kind option")
# repeat positional embeddings over whole batch
positional_embeddings = (
positional_embeddings
.reshape(1, frequencies, duration, -1)
.repeat(batch_size, 1, 1, 1))
if time_indexes is not None:
# use non default time indexes, can be used e.g. when performing
# predictions on sequences with a longer duration than the model's,
# allowing to bias its operation to avoid introducing attacks or
# releases in the middle of a longer sound
positional_embeddings = positional_embeddings[..., time_indexes, :]
if kind == Seq2SeqInputKind.Source:
positions_as_sequence = self.source_codemaps_helper.to_sequence(
positional_embeddings)
elif kind == Seq2SeqInputKind.Target:
positions_as_sequence = self.target_codemaps_helper.to_sequence(
positional_embeddings)
sequence_with_positions = torch.cat(
[sequence, positions_as_sequence],
dim=embedding_dim
)
return sequence_with_positions
def add_class_conditioning_to_sequence(
self, sequence_with_positions: torch.Tensor,
class_conditioning: Mapping[str, torch.Tensor]) -> torch.Tensor:
"""Overwrite the end of the positional embeddings with the class"""
embeddings = torch.zeros(
(*sequence_with_positions.shape[:2],
self.class_conditioning_total_dim),
device=sequence_with_positions.device)
for condition_name, class_condition in class_conditioning.items():
modality_embeddings = (
self.class_conditioning_embedding_layers[
condition_name](class_condition))
start_position = (
self.class_conditioning_start_positions_per_modality[
condition_name])
embeddings[
:, :, start_position:start_position+modality_embeddings.shape[2]] = (
modality_embeddings)
return torch.cat([sequence_with_positions, embeddings], dim=-1)
def add_start_symbol(self, sequence_with_positions: torch.Tensor,
kind: Seq2SeqInputKind,
class_conditioning: Mapping[str, torch.Tensor],
sequence_dim: int):
batch_size = sequence_with_positions.shape[0]
# combine time and frequency embeddings
if kind == Seq2SeqInputKind.Source:
start_symbol = self.source_start_symbol
transformer_sequence_length = (
self.source_transformer_sequence_length)
elif kind == Seq2SeqInputKind.Target:
start_symbol = self.target_start_symbol
transformer_sequence_length = (
self.target_transformer_sequence_length)
else:
raise ValueError(f"Unexpected value {kind} for kind option")
# repeat start-symbol over whole batch
start_symbol = start_symbol.repeat(batch_size, 1, 1)
if not self.local_class_conditioning:
if self.positional_class_conditioning:
start_symbol = self.add_class_conditioning_to_sequence(
start_symbol, class_conditioning
)
else:
# add conditioning tensors to start-symbol
for condition_name, class_condition in class_conditioning.items():
embeddings = (
self.class_conditioning_embedding_layers[
condition_name](class_condition)).squeeze(1)
start_position = (
self.class_conditioning_start_positions_per_modality[
condition_name])
start_symbol[:, :, start_position:start_position+embeddings.shape[1]] = embeddings.unsqueeze(1)
sequence_with_start_symbol = torch.cat(
[start_symbol,
sequence_with_positions],
dim=sequence_dim
)
return sequence_with_start_symbol
def make_class_conditioning_sequence(self,
class_conditioning: Mapping[
str, torch.Tensor],
) -> torch.Tensor:
"""Convert multi-modal class-conditioning maps to a single sequence
Class conditioning is only added to the source codemap
"""
kind = Seq2SeqInputKind.Source
if len(class_conditioning) == 0:
raise NotImplementedError
batch_size = list(class_conditioning.values())[0].shape[0]
embeddings = torch.zeros(batch_size, self.source_frequencies,
self.source_duration,
self.class_conditioning_total_dim
)
for condition_name, class_condition in class_conditioning.items():
condition_embeddings = (
self.class_conditioning_embedding_layers[
condition_name](class_condition))
start_position = (
self.class_conditioning_start_positions_per_modality[
condition_name])
end_position = start_position + condition_embeddings.shape[-1]
embeddings[..., start_position:end_position] = condition_embeddings
embeddings_sequence = self.source_codemaps_helper.to_sequence(
embeddings)
class_embeddings_sequence_with_positions = (
self.add_positions_to_sequence(embeddings_sequence,
kind=kind,
embedding_dim=-1))
return class_embeddings_sequence_with_positions
def forward(self, input: torch.Tensor,
condition: Optional[torch.Tensor] = None,
class_condition: Optional[torch.Tensor] = None,
memory: Optional[torch.Tensor] = None):
(batch_dim, sequence_dim) = (0, 1)
target_sequence: Optional[torch.Tensor]
if self.conditional_model:
target_sequence = input
source_sequence = condition
else:
source_sequence = input
target_sequence = None
assert source_sequence is not None
# transformer inputs are in time-major format
time_major_source_sequence = source_sequence.transpose(0, 1)
if target_sequence is not None:
time_major_target_sequence = target_sequence.transpose(0, 1)
if class_condition is not None:
time_major_class_condition_sequence = class_condition.transpose(0, 1)
else:
time_major_class_condition_sequence = None
(batch_dim, sequence_dim) = (1, 0)
memory_mask = None
causal_mask = self.causal_mask.to(input.device)
if self.conditional_model:
if self.use_identity_memory_mask:
memory_mask = self.identity_memory_mask
if memory is None:
src_mask = None
if self.self_conditional_model:
anti_causal_mask = causal_mask.t()
src_mask = anti_causal_mask
memory = self.transformer.encoder(
time_major_source_sequence,
mask=src_mask)
if self.use_relative_transformer:
memory, *encoder_attentions = memory
if time_major_class_condition_sequence is not None:
output_sequence = self.transformer.decoder(
time_major_target_sequence,
memory,
tgt_mask=causal_mask,
memory_mask=memory_mask,
condition=time_major_class_condition_sequence)
else:
output_sequence = self.transformer.decoder(
time_major_target_sequence,
memory,
tgt_mask=causal_mask,
memory_mask=memory_mask)
else:
output_sequence = self.transformer(time_major_source_sequence,
mask=causal_mask)
if self.use_relative_transformer:
output_sequence, *decoder_attentions = output_sequence
# trim start symbol
target_start_symbol_duration = self.target_start_symbol.shape[1]
output_sequence = output_sequence[target_start_symbol_duration-1:]
# trim last token, unused in next-token prediction task
output_sequence = output_sequence[:-1]
# transpose back to batch-major shape
output_sequence = output_sequence.transpose(
batch_dim, sequence_dim)
(batch_dim, sequence_dim) = (0, 1)
# convert outputs to class probabilities
logits = self.project_transformer_outputs_to_logits(output_sequence)
return logits, memory
@classmethod
def from_parameters_and_weights(
cls, parameters_json_path: pathlib.Path,
model_weights_checkpoint_path: pathlib.Path,
device: Union[str, torch.device] = 'cpu'
) -> 'VQNSynthTransformer':
"""Re-instantiate a stored model using init parameters and weights
Arguments:
parameters_json_path (pathlib.Path)
Path to the a json file containing the keyword arguments used
to initialize the object
model_weights_checkpoint_path (pathlib.Path)
Path to a model weights checkpoint file as created by
torch.save
device (str or torch.device, default 'cpu')
Device on which to load the stored weights
"""
with open(parameters_json_path, 'r') as f:
parameters = json.load(f)
model = cls(**parameters)
model_state_dict = torch.load(model_weights_checkpoint_path,
map_location=device)
if 'model' in model_state_dict.keys():
model_state_dict = model_state_dict['model']
model.load_state_dict(model_state_dict)
return model
def store_instantiation_parameters(self, path: pathlib.Path) -> None:
"""Store the parameters used to create this instance as JSON"""
with open(path, 'w') as f:
json.dump(self._instantiation_parameters, f, indent=4)
class SelfAttentiveVQTransformer(VQNSynthTransformer):
@property
def use_inpainting_mask_on_source(self) -> bool:
"""Use inpainting mask-token in self-attentive regeneration
"""
return True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.source_codemaps_helper = self.target_codemaps_helper = (
SimpleCodemapsHelper(self.source_frequencies,
self.source_duration)
)
class UpsamplingVQTransformer(VQNSynthTransformer):
@property
def use_inpainting_mask_on_source(self) -> bool:
"""No inpainting mask for upsampling Transformers
The whole conditioning information ishould bhe available since
upsampling is performed after generation of the conditioning source.
Only attention-masking is performed in the Upsampling Transformers.
"""
return False
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.source_codemaps_helper = SimpleCodemapsHelper(
self.source_frequencies,
self.source_duration)
self.target_codemaps_helper = ZigZagCodemapsHelper(
self.target_frequencies,
self.target_duration,
self.target_frequencies // self.source_frequencies,
self.target_duration // self.source_duration
) | interactive_spectrogram_inpainting/priors/transformer.py | from typing import Iterable, Mapping, Union, Optional, Tuple
import pathlib
import json
from abc import abstractmethod
from enum import Enum, auto
import torch
from torch import nn
from .codemaps_helpers import (CodemapsHelper,
SimpleCodemapsHelper, ZigZagCodemapsHelper)
from VQCPCB.transformer.transformer_custom import (
TransformerCustom, TransformerDecoderCustom, TransformerEncoderCustom,
TransformerDecoderLayerCustom, TransformerEncoderLayerCustom,
TransformerAlignedDecoderLayerCustom)
class Seq2SeqInputKind(Enum):
"""Types of input sequences for seq2seq models"""
Source = auto()
Target = auto()
class VQNSynthTransformer(nn.Module):
"""Transformer-based generative model for latent maps
Inputs are expected to be of shape [num_frequency_bands, time_duration],
with `sample[0, 0]` in the image the energy in the lowest frequency band
in the first time-frame.
Arguments:
* predict_frequencies_first (bool, optional, default is False):
if True, transposes the inputs to predict time-frame by time-frame,
potentially bringing more coherence in frequency within a given
time-frame by bringing the dependencies closer.
* predict_low_frequencies_first (bool, optional, default is True):
if False, flips the inputs so that frequencies are predicted in
decreasing order, starting at the harmonics.
* class_conditioning_num_classes_per_modality (iterable of int,
optional, default is None):
when using class-labels for conditioning, provide in this iterable
the number of classes per modality (e.g. pitch, instrument class...)
to intialize the embeddings layer
* class_conditioning_embedding_dim_per_modality (iterable of int,
optional, default is None):
when using class-labels for conditioning, provide in this iterable the
dimension of embeddings to use for each modality
"""
# helper attributes for appropriately flattening codemaps to sequences
source_codemaps_helper: SimpleCodemapsHelper
target_codemaps_helper: CodemapsHelper
@property
@abstractmethod
def use_inpainting_mask_on_source(self) -> bool:
"""Whether to introduce a specific masking token for the source sequences
This masking token is used to simulate partial information for
inpaiting operations.
"""
...
def __init__(
self,
shape: Iterable[int], # [num_frequencies, frame_duration]
n_class: int,
channel: int,
kernel_size: int,
n_block: int,
n_res_block: int,
res_channel: int,
attention: bool = True, # TODO: remove this parameter
dropout: float = 0.1,
n_cond_res_block: int = 0,
cond_res_channel: int = 0,
cond_res_kernel: int = 3,
n_out_res_block: int = 0,
predict_frequencies_first: bool = False,
predict_low_frequencies_first: bool = True,
d_model: int = 512,
embeddings_dim: int = 32,
positional_embeddings_dim: int = 16,
use_relative_transformer: bool = False,
class_conditioning_num_classes_per_modality: Optional[Mapping[str, int]] = None,
class_conditioning_embedding_dim_per_modality: Optional[Mapping[str, int]] = None,
class_conditioning_prepend_to_dummy_input: bool = False,
local_class_conditioning: bool = False,
positional_class_conditioning: bool = False,
add_mask_token_to_symbols: bool = False,
conditional_model: bool = False,
self_conditional_model: bool = False,
use_aligned_decoder: bool = False,
condition_shape: Optional[Tuple[int, int]] = None,
conditional_model_num_encoder_layers: int = 6,
conditional_model_num_decoder_layers: int = 8,
conditional_model_nhead: int = 8,
unconditional_model_num_encoder_layers: int = 6,
unconditional_model_nhead: int = 8,
use_identity_memory_mask: bool = False,
use_lstm_DEBUG: bool = False,
disable_start_symbol_DEBUG: bool = False,
):
if local_class_conditioning:
raise NotImplementedError(
"Depecrated in favor of positional class conditioning")
self.shape = shape
if self_conditional_model:
assert use_relative_transformer, (
"Self conditioning only meanigful for relative transformers")
assert conditional_model, (
"Self-conditioning is a specific case of conditioning")
assert (condition_shape is None or condition_shape == shape)
assert not (local_class_conditioning and positional_class_conditioning)
self.conditional_model = conditional_model
if self.conditional_model:
assert condition_shape is not None
self.self_conditional_model = self_conditional_model
self.use_relative_transformer = use_relative_transformer
if self.use_relative_transformer and not predict_frequencies_first:
raise (NotImplementedError,
"Relative positioning only implemented along time")
self.condition_shape = condition_shape
if self.self_conditional_model:
self.condition_shape = self.shape.copy()
self.local_class_conditioning = local_class_conditioning
self.positional_class_conditioning = positional_class_conditioning
self.n_class = n_class
self.channel = channel
if kernel_size % 2 == 0:
self.kernel_size = kernel_size + 1
else:
self.kernel_size = kernel_size
self.n_block = n_block
self.n_res_block = n_res_block
self.res_channel = res_channel
self.dropout = dropout
self.n_cond_res_block = n_cond_res_block
self.cond_res_channel = cond_res_channel
self.cond_res_kernel = cond_res_kernel
self.n_out_res_block = n_out_res_block
self.predict_frequencies_first = predict_frequencies_first
self.predict_low_frequencies_first = predict_low_frequencies_first
self.d_model = d_model
self.embeddings_dim = embeddings_dim
# ensure an even value
self.positional_embeddings_dim = 2 * (positional_embeddings_dim // 2)
self.class_conditioning_num_classes_per_modality = class_conditioning_num_classes_per_modality
self.class_conditioning_embedding_dim_per_modality = class_conditioning_embedding_dim_per_modality
self.class_conditioning_prepend_to_dummy_input = class_conditioning_prepend_to_dummy_input
# TODO(theis) unify to self.num_encoder_layers and self.n_head
# and find a better way to manage the different default values
self.conditional_model_num_encoder_layers = conditional_model_num_encoder_layers
self.conditional_model_nhead = conditional_model_nhead
self.conditional_model_num_decoder_layers = conditional_model_num_decoder_layers
self.use_identity_memory_mask = use_identity_memory_mask
self.use_aligned_decoder = use_aligned_decoder
self.use_lstm_DEBUG = use_lstm_DEBUG
self.disable_start_symbol_DEBUG = disable_start_symbol_DEBUG
self._instantiation_parameters = self.__dict__.copy()
super().__init__()
if self.use_inpainting_mask_on_source:
# add one token to the available source sequence symbols
self.n_class_source = self.n_class + 1
self.mask_token_index = self.n_class_source - 1
# generated, target sequences cannot contain the masking token
self.n_class_target = self.n_class
else:
self.n_class_target = self.n_class_source = self.n_class
if self.class_conditioning_num_classes_per_modality is not None:
self.class_conditioning_num_modalities = len(
self.class_conditioning_embedding_dim_per_modality.values())
self.class_conditioning_total_dim = sum(
self.class_conditioning_embedding_dim_per_modality.values())
else:
self.class_conditioning_num_modalities = 0
self.class_conditioning_total_dim = 0
self.source_frequencies, self.source_duration = (
self.condition_shape)
self.source_num_channels, self.source_num_events = (
1, self.source_frequencies * self.source_duration)
self.source_transformer_sequence_length = (
self.source_frequencies * self.source_duration)
self.target_frequencies, self.target_duration = self.shape
self.target_transformer_sequence_length = (
self.target_frequencies * self.target_duration)
self.target_events_per_source_patch = (
(self.target_duration // self.source_duration)
* (self.target_frequencies // self.source_frequencies)
)
self.target_num_channels = (
self.target_events_per_source_patch)
self.target_num_events = (
self.target_transformer_sequence_length
// self.target_num_channels)
# downsampling_factor = (
# (self.shape[0]*self.shape[1])
# // (self.condition_shape[0]*self.condition_shape[1]))
# else:
# self.target_num_channels = self.source_num_channels
# self.target_num_events = self.source_num_events
self.output_sizes = (-1, self.target_frequencies,
self.target_duration,
self.n_class_target)
self.source_positional_embeddings_frequency = nn.Parameter(
torch.randn((1, # batch-size
self.source_frequencies, # frequency-dimension
1, # time-dimension
self.positional_embeddings_dim//2))
)
self.source_positional_embeddings_time = nn.Parameter(
torch.randn((1, # batch-size
1, # frequency-dimension
self.source_duration, # time-dimension
self.positional_embeddings_dim//2))
)
self.target_positional_embeddings_time = None
# decoder-level, patch-based relative position embeddings
# allows to locate elements within a patch of the decoder
self.target_positional_embeddings_patch = nn.Parameter(
torch.randn((1, # batch-size
self.target_frequencies // self.source_frequencies, # frequency-dimension
self.target_duration // self.source_duration, # time-dimension
self.positional_embeddings_dim // 2))
)
self.target_positional_embeddings_frequency = nn.Parameter(
torch.randn((1, # batch-size
self.target_frequencies, # frequency-dimension
1, # time-dimension
self.positional_embeddings_dim // 2))
)
if self.embeddings_dim is None:
self.embeddings_dim = self.d_model-self.positional_embeddings_dim
self.source_embed = torch.nn.Embedding(self.n_class_source,
self.embeddings_dim)
self.embeddings_effective_dim = (self.d_model
- self.positional_embeddings_dim)
if self.positional_class_conditioning:
self.embeddings_effective_dim -= self.class_conditioning_total_dim
self.source_embeddings_linear = nn.Linear(
self.embeddings_dim,
self.embeddings_effective_dim
)
self.target_embeddings_linear = nn.Linear(
self.embeddings_dim,
self.embeddings_effective_dim)
self.target_embed = torch.nn.Embedding(self.n_class_target,
self.embeddings_dim)
# convert Transformer outputs to class-probabilities (as logits)
self.project_transformer_outputs_to_logits = (
nn.Linear(self.d_model, self.n_class_target))
self.class_conditioning_embedding_layers = nn.ModuleDict()
self.class_conditioning_class_to_index_per_modality = {}
self.class_conditioning_start_positions_per_modality = {}
if self.class_conditioning_num_classes_per_modality is not None:
# initialize class conditioning embedding layers
for (modality_name, modality_num_classes), modality_embedding_dim in zip(
self.class_conditioning_num_classes_per_modality.items(),
self.class_conditioning_embedding_dim_per_modality.values()):
self.class_conditioning_embedding_layers[modality_name] = (
torch.nn.Embedding(modality_num_classes,
modality_embedding_dim)
)
# initialize start positions for class conditioning in start symbol
if self.positional_class_conditioning or self.class_conditioning_prepend_to_dummy_input:
# insert class conditioning at beginning of the start symbol
current_position = 0
for modality_name, modality_embedding_dim in (
self.class_conditioning_embedding_dim_per_modality.items()):
self.class_conditioning_start_positions_per_modality[modality_name] = (
current_position
)
current_position = current_position + modality_embedding_dim
else:
raise NotImplementedError
# insert class conditioning at end of the start symbol
current_position = self.d_model
for modality_name, modality_embedding_dim in (
self.class_conditioning_embedding_dim_per_modality.items()):
current_position = current_position - modality_embedding_dim
self.class_conditioning_start_positions_per_modality[modality_name] = (
current_position
)
self.class_conditioning_total_dim_with_positions = (
self.class_conditioning_total_dim
+ self.positional_embeddings_dim)
self.source_start_symbol_dim = self.d_model
if self.positional_class_conditioning:
self.source_start_symbol_dim -= self.class_conditioning_total_dim
# TODO reduce dimensionality of start symbol and use a linear layer to expand it
self.source_start_symbol = nn.Parameter(
torch.randn((1, 1, self.source_start_symbol_dim))
)
self.source_num_events_with_start_symbol = self.source_num_events + 1
self.source_transformer_sequence_length_with_start_symbol = (
self.source_transformer_sequence_length + 1
)
self.target_start_symbol_dim = self.d_model
if self.positional_class_conditioning:
self.target_start_symbol_dim -= self.class_conditioning_total_dim
target_start_symbol_duration = self.target_events_per_source_patch
self.target_start_symbol = nn.Parameter(
torch.randn((1, target_start_symbol_duration,
self.target_start_symbol_dim))
)
self.target_num_events_with_start_symbol = (
self.target_num_events + 1
)
self.target_transformer_sequence_length_with_start_symbol = (
self.target_num_events_with_start_symbol
* self.target_num_channels
)
self.transformer: Union[nn.Transformer, nn.TransformerEncoder,
TransformerCustom, TransformerEncoderCustom]
if self.use_lstm_DEBUG:
raise NotImplementedError(
"TODO(theis), debug mode with simple LSTM layers")
else:
encoder_nhead = self.conditional_model_nhead
encoder_num_layers = self.conditional_model_num_encoder_layers
encoder_layer = TransformerEncoderLayerCustom(
d_model=self.d_model,
nhead=encoder_nhead,
attention_bias_type='relative_attention',
num_channels=self.source_num_channels,
num_events=self.source_num_events_with_start_symbol
)
relative_encoder = TransformerEncoderCustom(
encoder_layer=encoder_layer,
num_layers=encoder_num_layers
)
attention_bias_type_cross = 'relative_attention_target_source'
if self.use_identity_memory_mask:
attention_bias_type_cross = 'no_bias'
decoder_layer_implementation: nn.Module
if self.use_aligned_decoder:
# hierarchical decoder, use an aligned implementation
# this computes cross-attention only with tokens from the source
# that directly condition underlying tokens in the target
decoder_layer_implementation = (
TransformerAlignedDecoderLayerCustom)
else:
decoder_layer_implementation = (
TransformerDecoderLayerCustom)
decoder_layer = decoder_layer_implementation(
d_model=self.d_model,
nhead=self.conditional_model_nhead,
attention_bias_type_self='relative_attention',
attention_bias_type_cross=attention_bias_type_cross,
num_channels_encoder=self.source_num_channels,
num_events_encoder=self.source_num_events_with_start_symbol,
num_channels_decoder=self.target_num_channels,
num_events_decoder=self.target_num_events_with_start_symbol
)
custom_decoder = TransformerDecoderCustom(
decoder_layer=decoder_layer,
num_layers=self.conditional_model_num_decoder_layers
)
self.transformer = TransformerCustom(
nhead=self.conditional_model_nhead,
custom_encoder=relative_encoder,
custom_decoder=custom_decoder,
d_model=self.d_model)
def embed_data(self, input: torch.Tensor, kind: Seq2SeqInputKind) -> torch.Tensor:
if kind == Seq2SeqInputKind.Source:
return self.source_embeddings_linear(self.source_embed(input))
elif kind == Seq2SeqInputKind.Target and self.conditional_model:
return self.target_embeddings_linear(self.target_embed(input))
else:
raise ValueError(f"Unexpected value {kind} for kind option")
def _get_combined_positional_embeddings(self, kind: Seq2SeqInputKind) -> torch.Tensor:
if kind == Seq2SeqInputKind.Source:
positional_embeddings_frequency = (
self.source_positional_embeddings_frequency)
positional_embeddings_time = self.source_positional_embeddings_time
frequencies = self.source_frequencies
duration = self.source_duration
elif kind == Seq2SeqInputKind.Target and self.conditional_model:
positional_embeddings_frequency = (
self.target_positional_embeddings_frequency)
positional_embeddings_time = self.target_positional_embeddings_time
frequencies = self.target_frequencies
duration = self.target_duration
else:
raise ValueError(f"Unexpected value {kind} for kind option")
batch_dim, frequency_dim, time_dim, embedding_dim = (0, 1, 2, 3)
repeated_frequency_embeddings = (
positional_embeddings_frequency
.repeat(1, 1, duration, 1))
if not self.use_relative_transformer:
repeated_time_embeddings = (
positional_embeddings_time
.repeat(1, frequencies, 1, 1))
return torch.cat([repeated_frequency_embeddings,
repeated_time_embeddings],
dim=embedding_dim)
else:
if kind == Seq2SeqInputKind.Target:
positional_embeddings_patch = (
self.target_positional_embeddings_patch)
repeated_patch_embeddings = (
positional_embeddings_patch
.repeat(
1, self.source_frequencies, self.source_duration, 1)
)
return torch.cat([repeated_frequency_embeddings,
repeated_patch_embeddings],
dim=embedding_dim)
else:
return torch.cat([repeated_frequency_embeddings,
repeated_frequency_embeddings],
dim=embedding_dim)
@property
def combined_positional_embeddings_source(self) -> torch.Tensor:
return self._get_combined_positional_embeddings(Seq2SeqInputKind.Source)
@property
def combined_positional_embeddings_target(self) -> torch.Tensor:
return self._get_combined_positional_embeddings(Seq2SeqInputKind.Target)
@property
def causal_mask(self) -> torch.Tensor:
"""Generate a mask to impose causality"""
if self.conditional_model:
# masking is applied only on the target, access is allowed to
# all positions on the conditioning input
causal_mask_length = (
self.target_transformer_sequence_length_with_start_symbol)
else:
# apply causal mask to the input for the prediction task
causal_mask_length = (
self.source_transformer_sequence_length_with_start_symbol)
mask = (torch.triu(torch.ones(causal_mask_length,
causal_mask_length)) == 1
).transpose(0, 1)
mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(
mask == 1, float(0.0))
return mask
@property
def identity_memory_mask(self) -> torch.Tensor:
identity_memory_mask = (
torch.eye(self.source_transformer_sequence_length_with_start_symbol).float())
identity_memory_mask = (
identity_memory_mask
.masked_fill(identity_memory_mask == 0, float('-inf'))
.masked_fill(identity_memory_mask == 1, float(0.0))
)
return identity_memory_mask
def to_sequences(self, input: torch.Tensor,
condition: Optional[torch.Tensor] = None,
class_conditioning: Mapping[str, torch.Tensor] = {},
mask: Optional[torch.BoolTensor] = None,
time_indexes_source: Optional[Iterable[int]] = None,
time_indexes_target: Optional[Iterable[int]] = None,
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
source_sequence = self.source_codemaps_helper.to_sequence(condition)
if mask is not None and self.use_inpainting_mask_on_source:
mask_sequence = self.source_codemaps_helper.to_sequence(mask)
else:
mask_sequence = None
source_sequence, _ = self.prepare_data(
source_sequence, kind=Seq2SeqInputKind.Source,
class_conditioning=class_conditioning,
mask=mask_sequence,
time_indexes=time_indexes_source)
target_sequence = self.target_codemaps_helper.to_sequence(input)
target_sequence, _ = self.prepare_data(
target_sequence, kind=Seq2SeqInputKind.Target,
class_conditioning=class_conditioning,
time_indexes=time_indexes_target)
return source_sequence, target_sequence
def prepare_data(self, sequence: torch.Tensor, kind: Seq2SeqInputKind,
class_conditioning: Mapping[str, torch.Tensor] = {},
mask: Optional[torch.Tensor] = None,
time_indexes: Optional[Iterable[int]] = None
) -> torch.Tensor:
if mask is not None:
sequence = sequence.masked_fill(mask, self.mask_token_index)
(batch_dim, sequence_dim, embedding_dim) = (0, 1, 2)
embedded_sequence = self.embed_data(sequence, kind=kind)
embedded_sequence_with_positions = self.add_positions_to_sequence(
embedded_sequence, kind=kind, embedding_dim=embedding_dim,
time_indexes=time_indexes
)
if self.positional_class_conditioning:
embedded_sequence_with_positions = (
self.add_class_conditioning_to_sequence(
embedded_sequence_with_positions,
class_conditioning)
)
prepared_sequence = self.add_start_symbol(
embedded_sequence_with_positions, kind=kind,
class_conditioning=class_conditioning, sequence_dim=1
)
frequency_dim, time_dim = (2, 1)
return prepared_sequence, (
(batch_dim, frequency_dim, time_dim))
def add_positions_to_sequence(self, sequence: torch.Tensor,
kind: Seq2SeqInputKind,
embedding_dim: int,
time_indexes: Optional[Iterable[int]]):
# add positional embeddings
batch_size = sequence.shape[0]
# combine time and frequency embeddings
if kind == Seq2SeqInputKind.Source:
frequencies = self.source_frequencies
duration = self.source_duration
positional_embeddings = self.combined_positional_embeddings_source
transformer_sequence_length = (
self.source_transformer_sequence_length)
elif kind == Seq2SeqInputKind.Target:
frequencies = self.target_frequencies
duration = self.target_duration
positional_embeddings = self.combined_positional_embeddings_target
transformer_sequence_length = (
self.target_transformer_sequence_length)
else:
raise ValueError(f"Unexpected value {kind} for kind option")
# repeat positional embeddings over whole batch
positional_embeddings = (
positional_embeddings
.reshape(1, frequencies, duration, -1)
.repeat(batch_size, 1, 1, 1))
if time_indexes is not None:
# use non default time indexes, can be used e.g. when performing
# predictions on sequences with a longer duration than the model's,
# allowing to bias its operation to avoid introducing attacks or
# releases in the middle of a longer sound
positional_embeddings = positional_embeddings[..., time_indexes, :]
if kind == Seq2SeqInputKind.Source:
positions_as_sequence = self.source_codemaps_helper.to_sequence(
positional_embeddings)
elif kind == Seq2SeqInputKind.Target:
positions_as_sequence = self.target_codemaps_helper.to_sequence(
positional_embeddings)
sequence_with_positions = torch.cat(
[sequence, positions_as_sequence],
dim=embedding_dim
)
return sequence_with_positions
def add_class_conditioning_to_sequence(
self, sequence_with_positions: torch.Tensor,
class_conditioning: Mapping[str, torch.Tensor]) -> torch.Tensor:
"""Overwrite the end of the positional embeddings with the class"""
embeddings = torch.zeros(
(*sequence_with_positions.shape[:2],
self.class_conditioning_total_dim),
device=sequence_with_positions.device)
for condition_name, class_condition in class_conditioning.items():
modality_embeddings = (
self.class_conditioning_embedding_layers[
condition_name](class_condition))
start_position = (
self.class_conditioning_start_positions_per_modality[
condition_name])
embeddings[
:, :, start_position:start_position+modality_embeddings.shape[2]] = (
modality_embeddings)
return torch.cat([sequence_with_positions, embeddings], dim=-1)
def add_start_symbol(self, sequence_with_positions: torch.Tensor,
kind: Seq2SeqInputKind,
class_conditioning: Mapping[str, torch.Tensor],
sequence_dim: int):
batch_size = sequence_with_positions.shape[0]
# combine time and frequency embeddings
if kind == Seq2SeqInputKind.Source:
start_symbol = self.source_start_symbol
transformer_sequence_length = (
self.source_transformer_sequence_length)
elif kind == Seq2SeqInputKind.Target:
start_symbol = self.target_start_symbol
transformer_sequence_length = (
self.target_transformer_sequence_length)
else:
raise ValueError(f"Unexpected value {kind} for kind option")
# repeat start-symbol over whole batch
start_symbol = start_symbol.repeat(batch_size, 1, 1)
if not self.local_class_conditioning:
if self.positional_class_conditioning:
start_symbol = self.add_class_conditioning_to_sequence(
start_symbol, class_conditioning
)
else:
# add conditioning tensors to start-symbol
for condition_name, class_condition in class_conditioning.items():
embeddings = (
self.class_conditioning_embedding_layers[
condition_name](class_condition)).squeeze(1)
start_position = (
self.class_conditioning_start_positions_per_modality[
condition_name])
start_symbol[:, :, start_position:start_position+embeddings.shape[1]] = embeddings.unsqueeze(1)
sequence_with_start_symbol = torch.cat(
[start_symbol,
sequence_with_positions],
dim=sequence_dim
)
return sequence_with_start_symbol
def make_class_conditioning_sequence(self,
class_conditioning: Mapping[
str, torch.Tensor],
) -> torch.Tensor:
"""Convert multi-modal class-conditioning maps to a single sequence
Class conditioning is only added to the source codemap
"""
kind = Seq2SeqInputKind.Source
if len(class_conditioning) == 0:
raise NotImplementedError
batch_size = list(class_conditioning.values())[0].shape[0]
embeddings = torch.zeros(batch_size, self.source_frequencies,
self.source_duration,
self.class_conditioning_total_dim
)
for condition_name, class_condition in class_conditioning.items():
condition_embeddings = (
self.class_conditioning_embedding_layers[
condition_name](class_condition))
start_position = (
self.class_conditioning_start_positions_per_modality[
condition_name])
end_position = start_position + condition_embeddings.shape[-1]
embeddings[..., start_position:end_position] = condition_embeddings
embeddings_sequence = self.source_codemaps_helper.to_sequence(
embeddings)
class_embeddings_sequence_with_positions = (
self.add_positions_to_sequence(embeddings_sequence,
kind=kind,
embedding_dim=-1))
return class_embeddings_sequence_with_positions
def forward(self, input: torch.Tensor,
condition: Optional[torch.Tensor] = None,
class_condition: Optional[torch.Tensor] = None,
memory: Optional[torch.Tensor] = None):
(batch_dim, sequence_dim) = (0, 1)
target_sequence: Optional[torch.Tensor]
if self.conditional_model:
target_sequence = input
source_sequence = condition
else:
source_sequence = input
target_sequence = None
assert source_sequence is not None
# transformer inputs are in time-major format
time_major_source_sequence = source_sequence.transpose(0, 1)
if target_sequence is not None:
time_major_target_sequence = target_sequence.transpose(0, 1)
if class_condition is not None:
time_major_class_condition_sequence = class_condition.transpose(0, 1)
else:
time_major_class_condition_sequence = None
(batch_dim, sequence_dim) = (1, 0)
memory_mask = None
causal_mask = self.causal_mask.to(input.device)
if self.conditional_model:
if self.use_identity_memory_mask:
memory_mask = self.identity_memory_mask
if memory is None:
src_mask = None
if self.self_conditional_model:
anti_causal_mask = causal_mask.t()
src_mask = anti_causal_mask
memory = self.transformer.encoder(
time_major_source_sequence,
mask=src_mask)
if self.use_relative_transformer:
memory, *encoder_attentions = memory
if time_major_class_condition_sequence is not None:
output_sequence = self.transformer.decoder(
time_major_target_sequence,
memory,
tgt_mask=causal_mask,
memory_mask=memory_mask,
condition=time_major_class_condition_sequence)
else:
output_sequence = self.transformer.decoder(
time_major_target_sequence,
memory,
tgt_mask=causal_mask,
memory_mask=memory_mask)
else:
output_sequence = self.transformer(time_major_source_sequence,
mask=causal_mask)
if self.use_relative_transformer:
output_sequence, *decoder_attentions = output_sequence
# trim start symbol
target_start_symbol_duration = self.target_start_symbol.shape[1]
output_sequence = output_sequence[target_start_symbol_duration-1:]
# trim last token, unused in next-token prediction task
output_sequence = output_sequence[:-1]
# transpose back to batch-major shape
output_sequence = output_sequence.transpose(
batch_dim, sequence_dim)
(batch_dim, sequence_dim) = (0, 1)
# convert outputs to class probabilities
logits = self.project_transformer_outputs_to_logits(output_sequence)
return logits, memory
@classmethod
def from_parameters_and_weights(
cls, parameters_json_path: pathlib.Path,
model_weights_checkpoint_path: pathlib.Path,
device: Union[str, torch.device] = 'cpu'
) -> 'VQNSynthTransformer':
"""Re-instantiate a stored model using init parameters and weights
Arguments:
parameters_json_path (pathlib.Path)
Path to the a json file containing the keyword arguments used
to initialize the object
model_weights_checkpoint_path (pathlib.Path)
Path to a model weights checkpoint file as created by
torch.save
device (str or torch.device, default 'cpu')
Device on which to load the stored weights
"""
with open(parameters_json_path, 'r') as f:
parameters = json.load(f)
model = cls(**parameters)
model_state_dict = torch.load(model_weights_checkpoint_path,
map_location=device)
if 'model' in model_state_dict.keys():
model_state_dict = model_state_dict['model']
model.load_state_dict(model_state_dict)
return model
def store_instantiation_parameters(self, path: pathlib.Path) -> None:
"""Store the parameters used to create this instance as JSON"""
with open(path, 'w') as f:
json.dump(self._instantiation_parameters, f, indent=4)
class SelfAttentiveVQTransformer(VQNSynthTransformer):
@property
def use_inpainting_mask_on_source(self) -> bool:
"""Use inpainting mask-token in self-attentive regeneration
"""
return True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.source_codemaps_helper = self.target_codemaps_helper = (
SimpleCodemapsHelper(self.source_frequencies,
self.source_duration)
)
class UpsamplingVQTransformer(VQNSynthTransformer):
@property
def use_inpainting_mask_on_source(self) -> bool:
"""No inpainting mask for upsampling Transformers
The whole conditioning information ishould bhe available since
upsampling is performed after generation of the conditioning source.
Only attention-masking is performed in the Upsampling Transformers.
"""
return False
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.source_codemaps_helper = SimpleCodemapsHelper(
self.source_frequencies,
self.source_duration)
self.target_codemaps_helper = ZigZagCodemapsHelper(
self.target_frequencies,
self.target_duration,
self.target_frequencies // self.source_frequencies,
self.target_duration // self.source_duration
) | 0.853027 | 0.38856 |
!pip install wandb -qqq
import wandb
wandb.init(project="Back_Propagation", entity="cs20m040")
!wandb login fb3bb8a505ba908b667b747ed68e4b154b2f6fc5
from tqdm.notebook import tqdm
from sklearn.preprocessing import OneHotEncoder
from keras.datasets import fashion_mnist
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
import pandas as pd
import math
config_defaults={
'epochs' : 10,
'batch_size' : 128,
'learning_rate' : .001,
'hidden_sizes' : [64]
}
wandb.init(config=config_defaults)
config = wandb.config
# give class name for all image categories
class_names = {i:cn for i, cn in enumerate(['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']) }
#load the dataset
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
# reshape dataset to have a single channel
X_train = x_train.reshape(x_train.shape[0], 1, x_train.shape[1] * x_train.shape[2])
X_test = x_test.reshape(x_test.shape[0], 1, x_test.shape[1] * x_test.shape[2])
# Convert from integers to floats
x_train = x_train.astype(np.float64)
x_test = x_test.astype(np.float64)
# scale the values between 0 and 1 for both training and testing set
x_train = x_train / 255.0
x_test = x_test / 255.0
enc = OneHotEncoder()
# 0 -> (1, 0, 0, 0), 1 -> (0, 1, 0, 0), 2 -> (0, 0, 1, 0), 3 -> (0, 0, 0, 1)
y_OH_train = enc.fit_transform(np.expand_dims(y_train,1)).toarray()
y_OH_val = enc.fit_transform(np.expand_dims(y_test,1)).toarray()
def plot(images, labels, predictions=None):
# create a grid with 5 columns
n_cols = min(5, len(images))
n_rows = math.ceil(len(images) / n_cols)
fig, axes = plt.subplots(n_rows, n_cols, figsize=(n_cols+3, n_rows+4))
if predictions is None:
predictions = [None] * len(labels)
# plot images
for i, (x, y_true, y_pred) in enumerate(zip(images, labels, predictions)):
# plot all images in a single loop
ax = axes.flat[i]
ax.imshow(x, cmap=plt.cm.binary)
ax.set_title(f"Lbl: {class_names[y_true]}")
if y_pred is not None:
ax.set_xlabel(f"pred: {class_names[y_pred]}")
ax.set_xticks([])
ax.set_yticks([])
# plot first few images
plot(x_train[:10], y_train[:10])
class FFSN_MultiClass:
def __init__(self, n_inputs, n_outputs, hidden_sizes=[3]):
self.nx = n_inputs
self.ny = n_outputs
self.nh = len(hidden_sizes)
self.sizes = [self.nx] + hidden_sizes + [self.ny]
self.W = {}
self.B = {}
for i in range(self.nh+1):
self.W[i+1] = np.random.randn(self.sizes[i], self.sizes[i+1])
self.B[i+1] = np.zeros((1, self.sizes[i+1]))
def sigmoid(self, x):
return 1.0/(1.0 + np.exp(-x))
def softmax(self, x):
exps = np.exp(x)
return exps / np.sum(exps)
def forward_pass(self, x):
self.A = {}
self.H = {}
self.H[0] = x.reshape(1, -1)
for i in range(self.nh):
self.A[i+1] = np.matmul(self.H[i], self.W[i+1]) + self.B[i+1]
self.H[i+1] = self.sigmoid(self.A[i+1])
self.A[self.nh+1] = np.matmul(self.H[self.nh], self.W[self.nh+1]) + self.B[self.nh+1]
self.H[self.nh+1] = self.softmax(self.A[self.nh+1])
return self.H[self.nh+1]
def grad(self, x, y):
self.forward_pass(x)
self.dW = {}
self.dB = {}
self.dH = {}
self.dA = {}
L = self.nh + 1
self.dA[L] = (self.H[L] - y)
for k in range(L, 0, -1):
self.dW[k] = np.matmul(self.H[k-1].T, self.dA[k])
self.dB[k] = self.dA[k]
self.dH[k-1] = np.matmul(self.dA[k], self.W[k].T)
self.dA[k-1] = np.multiply(self.dH[k-1], self.grad_sigmoid(self.H[k-1]))
def predict(self, X):
Y_pred = []
for x in X:
y_pred = self.forward_pass(x)
Y_pred.append(y_pred)
return np.array(Y_pred).squeeze()
def grad_sigmoid(self, x):
return x*(1-x)
def cross_entropy(self,label,pred):
yl=np.multiply(pred,label)
yl=yl[yl!=0]
yl=-np.log(yl)
yl=np.mean(yl)
return yl
def fit(self, X, Y, epochs=10, initialize='True', learning_rate=0.05, display_loss=False):
if display_loss:
loss = {}
if initialize:
for i in range(self.nh+1):
self.W[i+1] = np.random.randn(self.sizes[i], self.sizes[i+1])
self.B[i+1] = np.zeros((1, self.sizes[i+1]))
for epoch in tqdm(range(epochs), total=epochs, unit="epoch"):
dW = {}
dB = {}
for i in range(self.nh+1):
dW[i+1] = np.zeros((self.sizes[i], self.sizes[i+1]))
dB[i+1] = np.zeros((1, self.sizes[i+1]))
for x, y in zip(X, Y):
self.grad(x, y)
for i in range(self.nh+1):
dW[i+1] += self.dW[i+1]
dB[i+1] += self.dB[i+1]
m = X.shape[1]
for i in range(self.nh+1):
self.W[i+1] -= learning_rate * (dW[i+1]/m)
self.B[i+1] -= learning_rate * (dB[i+1]/m)
if display_loss:
Y_pred = self.predict(X)
loss[epoch] = self.cross_entropy(Y, Y_pred)
if display_loss:
#plt.plot(loss.values())
plt.plot(np.array(list(loss.values())).astype(float))
plt.xlabel('Epochs')
plt.ylabel('Cross Entropy')
plt.show()
#train the network
from sklearn.metrics import accuracy_score
ffsn_multi = FFSN_MultiClass(X_train.shape[2], y_OH_train.shape[1], hidden_sizes=config.hidden_sizes)
ffsn_multi.fit(x_train, y_OH_train, epochs=config.epochs,
learning_rate=config.learning_rate,
display_loss=True,
)
Y_pred_train = ffsn_multi.predict(x_train)
Y_pred_train = np.argmax(Y_pred_train,1)
Y_pred_val = ffsn_multi.predict(x_test)
Y_pred_val = np.argmax(Y_pred_val,1)
accuracy_train = accuracy_score(Y_pred_train, y_train)
accuracy_val = accuracy_score(Y_pred_val, y_test)
print("Training accuracy", round(accuracy_train, 4))
print("Validation accuracy", round(accuracy_val, 4))
# plot 20 random data
rand_idxs = np.random.permutation(len(x_test))[:20]
plot(x_test[rand_idxs], y_test[rand_idxs], Y_pred_val[rand_idxs]) | FeedForwardNetwork.py | !pip install wandb -qqq
import wandb
wandb.init(project="Back_Propagation", entity="cs20m040")
!wandb login fb3bb8a505ba908b667b747ed68e4b154b2f6fc5
from tqdm.notebook import tqdm
from sklearn.preprocessing import OneHotEncoder
from keras.datasets import fashion_mnist
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
import pandas as pd
import math
config_defaults={
'epochs' : 10,
'batch_size' : 128,
'learning_rate' : .001,
'hidden_sizes' : [64]
}
wandb.init(config=config_defaults)
config = wandb.config
# give class name for all image categories
class_names = {i:cn for i, cn in enumerate(['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']) }
#load the dataset
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
# reshape dataset to have a single channel
X_train = x_train.reshape(x_train.shape[0], 1, x_train.shape[1] * x_train.shape[2])
X_test = x_test.reshape(x_test.shape[0], 1, x_test.shape[1] * x_test.shape[2])
# Convert from integers to floats
x_train = x_train.astype(np.float64)
x_test = x_test.astype(np.float64)
# scale the values between 0 and 1 for both training and testing set
x_train = x_train / 255.0
x_test = x_test / 255.0
enc = OneHotEncoder()
# 0 -> (1, 0, 0, 0), 1 -> (0, 1, 0, 0), 2 -> (0, 0, 1, 0), 3 -> (0, 0, 0, 1)
y_OH_train = enc.fit_transform(np.expand_dims(y_train,1)).toarray()
y_OH_val = enc.fit_transform(np.expand_dims(y_test,1)).toarray()
def plot(images, labels, predictions=None):
# create a grid with 5 columns
n_cols = min(5, len(images))
n_rows = math.ceil(len(images) / n_cols)
fig, axes = plt.subplots(n_rows, n_cols, figsize=(n_cols+3, n_rows+4))
if predictions is None:
predictions = [None] * len(labels)
# plot images
for i, (x, y_true, y_pred) in enumerate(zip(images, labels, predictions)):
# plot all images in a single loop
ax = axes.flat[i]
ax.imshow(x, cmap=plt.cm.binary)
ax.set_title(f"Lbl: {class_names[y_true]}")
if y_pred is not None:
ax.set_xlabel(f"pred: {class_names[y_pred]}")
ax.set_xticks([])
ax.set_yticks([])
# plot first few images
plot(x_train[:10], y_train[:10])
class FFSN_MultiClass:
def __init__(self, n_inputs, n_outputs, hidden_sizes=[3]):
self.nx = n_inputs
self.ny = n_outputs
self.nh = len(hidden_sizes)
self.sizes = [self.nx] + hidden_sizes + [self.ny]
self.W = {}
self.B = {}
for i in range(self.nh+1):
self.W[i+1] = np.random.randn(self.sizes[i], self.sizes[i+1])
self.B[i+1] = np.zeros((1, self.sizes[i+1]))
def sigmoid(self, x):
return 1.0/(1.0 + np.exp(-x))
def softmax(self, x):
exps = np.exp(x)
return exps / np.sum(exps)
def forward_pass(self, x):
self.A = {}
self.H = {}
self.H[0] = x.reshape(1, -1)
for i in range(self.nh):
self.A[i+1] = np.matmul(self.H[i], self.W[i+1]) + self.B[i+1]
self.H[i+1] = self.sigmoid(self.A[i+1])
self.A[self.nh+1] = np.matmul(self.H[self.nh], self.W[self.nh+1]) + self.B[self.nh+1]
self.H[self.nh+1] = self.softmax(self.A[self.nh+1])
return self.H[self.nh+1]
def grad(self, x, y):
self.forward_pass(x)
self.dW = {}
self.dB = {}
self.dH = {}
self.dA = {}
L = self.nh + 1
self.dA[L] = (self.H[L] - y)
for k in range(L, 0, -1):
self.dW[k] = np.matmul(self.H[k-1].T, self.dA[k])
self.dB[k] = self.dA[k]
self.dH[k-1] = np.matmul(self.dA[k], self.W[k].T)
self.dA[k-1] = np.multiply(self.dH[k-1], self.grad_sigmoid(self.H[k-1]))
def predict(self, X):
Y_pred = []
for x in X:
y_pred = self.forward_pass(x)
Y_pred.append(y_pred)
return np.array(Y_pred).squeeze()
def grad_sigmoid(self, x):
return x*(1-x)
def cross_entropy(self,label,pred):
yl=np.multiply(pred,label)
yl=yl[yl!=0]
yl=-np.log(yl)
yl=np.mean(yl)
return yl
def fit(self, X, Y, epochs=10, initialize='True', learning_rate=0.05, display_loss=False):
if display_loss:
loss = {}
if initialize:
for i in range(self.nh+1):
self.W[i+1] = np.random.randn(self.sizes[i], self.sizes[i+1])
self.B[i+1] = np.zeros((1, self.sizes[i+1]))
for epoch in tqdm(range(epochs), total=epochs, unit="epoch"):
dW = {}
dB = {}
for i in range(self.nh+1):
dW[i+1] = np.zeros((self.sizes[i], self.sizes[i+1]))
dB[i+1] = np.zeros((1, self.sizes[i+1]))
for x, y in zip(X, Y):
self.grad(x, y)
for i in range(self.nh+1):
dW[i+1] += self.dW[i+1]
dB[i+1] += self.dB[i+1]
m = X.shape[1]
for i in range(self.nh+1):
self.W[i+1] -= learning_rate * (dW[i+1]/m)
self.B[i+1] -= learning_rate * (dB[i+1]/m)
if display_loss:
Y_pred = self.predict(X)
loss[epoch] = self.cross_entropy(Y, Y_pred)
if display_loss:
#plt.plot(loss.values())
plt.plot(np.array(list(loss.values())).astype(float))
plt.xlabel('Epochs')
plt.ylabel('Cross Entropy')
plt.show()
#train the network
from sklearn.metrics import accuracy_score
ffsn_multi = FFSN_MultiClass(X_train.shape[2], y_OH_train.shape[1], hidden_sizes=config.hidden_sizes)
ffsn_multi.fit(x_train, y_OH_train, epochs=config.epochs,
learning_rate=config.learning_rate,
display_loss=True,
)
Y_pred_train = ffsn_multi.predict(x_train)
Y_pred_train = np.argmax(Y_pred_train,1)
Y_pred_val = ffsn_multi.predict(x_test)
Y_pred_val = np.argmax(Y_pred_val,1)
accuracy_train = accuracy_score(Y_pred_train, y_train)
accuracy_val = accuracy_score(Y_pred_val, y_test)
print("Training accuracy", round(accuracy_train, 4))
print("Validation accuracy", round(accuracy_val, 4))
# plot 20 random data
rand_idxs = np.random.permutation(len(x_test))[:20]
plot(x_test[rand_idxs], y_test[rand_idxs], Y_pred_val[rand_idxs]) | 0.597373 | 0.37777 |
# Copyright (C) 2016 ETH Zurich, Institute for Astronomy
# System imports
from __future__ import print_function, division, absolute_import, unicode_literals
__author__ = 'sibirrer'
from MultiLens.Cosmo.cosmo import CosmoProp
import MultiLens.Utils.constants as const
class LensObject(object):
"""
class to specify the deflection caused by this object
"""
def __init__(self, redshift, type='point_mass', approximation='weak', main=False, observer_frame=True):
self.redshift = redshift
self.type = type
self.approximation = approximation
self.kwargs_param = dict([])
self.main = main
self.observer_frame = observer_frame
if type == 'point_mass':
from MultiLens.Profiles.point_mass import PointMass
self.func = PointMass()
elif type == 'NFW':
from MultiLens.Profiles.nfw import NFW
self.func = NFW()
elif type == 'SIS':
from MultiLens.Profiles.SIS import SIS
self.func = SIS()
else:
raise ValueError("lens type %s not valid." % type)
self.cosmo = CosmoProp()
def add_info(self, name, data):
"""
adds info (i.e. parameters of the lens object
:return:
"""
if name == 'kwargs_profile':
self.kwargs_param = data
if self.observer_frame and 'pos_x' in data and 'pos_y' in data:
self.pos_x_observer = data['pos_x']*const.arcsec
self.pos_y_observer = data['pos_y']*const.arcsec
self.kwargs_param['pos_x'] = self.cosmo.arcsec2phys(data['pos_x'], z=self.redshift)
self.kwargs_param['pos_y'] = self.cosmo.arcsec2phys(data['pos_y'], z=self.redshift)
else:
print("name %s is not a valid info attribute." % name)
def potential(self, x, y):
"""
returns the lensing potential of the object
:param x: x-coordinate of the light ray
:param y: y-coordinate of the light ray
:return: potential
"""
f_ = self.func.function(x, y, **self.kwargs_param)
return f_
def deflection(self, x, y):
"""
returns the deflection of the object
:param x: x-coordinate of the light ray
:param y: y-coordinate of the light ray
:return: delta_x, delta_y
"""
f_x0, f_y0 = self.func.derivative(0, 0, **self.kwargs_param)
f_x, f_y = self.func.derivative(x, y, **self.kwargs_param)
return f_x-f_x0, f_y-f_y0
def distortion(self, x, y):
"""
returns the distortion matrix
:param x: x-coordinate of the light ray
:param y: y-coordinate of the light ray
:return:
"""
f_xx, f_yy, f_xy = self.func.hessian(x, y, **self.kwargs_param)
return f_xx, f_yy, f_xy
def position(self):
"""
returns x_pos, y_pos
:return:
"""
if self.observer_frame and hasattr(self, 'pos_x_observer') and hasattr(self, 'pos_y_observer'):
return self.pos_x_observer, self.pos_y_observer
else:
return 0, 0
def update_position(self, pos_x, pos_y):
"""
updates the positional information with the new (unlensed) positions
:param pos_x:
:param pos_y:
:return:
"""
if self.observer_frame:
self.kwargs_param['pos_x'] = pos_x
self.kwargs_param['pos_y'] = pos_y
def reset_position(self):
"""
reset position to the one of the observer
:return:
"""
self.kwargs_param['pos_x'] = self.cosmo.arcsec2phys(self.pos_x_observer/const.arcsec, z=self.redshift)
self.kwargs_param['pos_y'] = self.cosmo.arcsec2phys(self.pos_y_observer/const.arcsec, z=self.redshift)
def print_info(self):
"""
print all the information about the lens
:return:
"""
print('==========')
if self.main is True:
print("This is the main deflector.")
print("redshift = ", self.redshift)
print("type = ", self.type)
print("approximation: ", self.approximation)
print("parameters: ", self.kwargs_param) | MultiLens/lens_object.py |
# Copyright (C) 2016 ETH Zurich, Institute for Astronomy
# System imports
from __future__ import print_function, division, absolute_import, unicode_literals
__author__ = 'sibirrer'
from MultiLens.Cosmo.cosmo import CosmoProp
import MultiLens.Utils.constants as const
class LensObject(object):
"""
class to specify the deflection caused by this object
"""
def __init__(self, redshift, type='point_mass', approximation='weak', main=False, observer_frame=True):
self.redshift = redshift
self.type = type
self.approximation = approximation
self.kwargs_param = dict([])
self.main = main
self.observer_frame = observer_frame
if type == 'point_mass':
from MultiLens.Profiles.point_mass import PointMass
self.func = PointMass()
elif type == 'NFW':
from MultiLens.Profiles.nfw import NFW
self.func = NFW()
elif type == 'SIS':
from MultiLens.Profiles.SIS import SIS
self.func = SIS()
else:
raise ValueError("lens type %s not valid." % type)
self.cosmo = CosmoProp()
def add_info(self, name, data):
"""
adds info (i.e. parameters of the lens object
:return:
"""
if name == 'kwargs_profile':
self.kwargs_param = data
if self.observer_frame and 'pos_x' in data and 'pos_y' in data:
self.pos_x_observer = data['pos_x']*const.arcsec
self.pos_y_observer = data['pos_y']*const.arcsec
self.kwargs_param['pos_x'] = self.cosmo.arcsec2phys(data['pos_x'], z=self.redshift)
self.kwargs_param['pos_y'] = self.cosmo.arcsec2phys(data['pos_y'], z=self.redshift)
else:
print("name %s is not a valid info attribute." % name)
def potential(self, x, y):
"""
returns the lensing potential of the object
:param x: x-coordinate of the light ray
:param y: y-coordinate of the light ray
:return: potential
"""
f_ = self.func.function(x, y, **self.kwargs_param)
return f_
def deflection(self, x, y):
"""
returns the deflection of the object
:param x: x-coordinate of the light ray
:param y: y-coordinate of the light ray
:return: delta_x, delta_y
"""
f_x0, f_y0 = self.func.derivative(0, 0, **self.kwargs_param)
f_x, f_y = self.func.derivative(x, y, **self.kwargs_param)
return f_x-f_x0, f_y-f_y0
def distortion(self, x, y):
"""
returns the distortion matrix
:param x: x-coordinate of the light ray
:param y: y-coordinate of the light ray
:return:
"""
f_xx, f_yy, f_xy = self.func.hessian(x, y, **self.kwargs_param)
return f_xx, f_yy, f_xy
def position(self):
"""
returns x_pos, y_pos
:return:
"""
if self.observer_frame and hasattr(self, 'pos_x_observer') and hasattr(self, 'pos_y_observer'):
return self.pos_x_observer, self.pos_y_observer
else:
return 0, 0
def update_position(self, pos_x, pos_y):
"""
updates the positional information with the new (unlensed) positions
:param pos_x:
:param pos_y:
:return:
"""
if self.observer_frame:
self.kwargs_param['pos_x'] = pos_x
self.kwargs_param['pos_y'] = pos_y
def reset_position(self):
"""
reset position to the one of the observer
:return:
"""
self.kwargs_param['pos_x'] = self.cosmo.arcsec2phys(self.pos_x_observer/const.arcsec, z=self.redshift)
self.kwargs_param['pos_y'] = self.cosmo.arcsec2phys(self.pos_y_observer/const.arcsec, z=self.redshift)
def print_info(self):
"""
print all the information about the lens
:return:
"""
print('==========')
if self.main is True:
print("This is the main deflector.")
print("redshift = ", self.redshift)
print("type = ", self.type)
print("approximation: ", self.approximation)
print("parameters: ", self.kwargs_param) | 0.874721 | 0.337285 |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='rsb_event.proto',
package='Rsh',
syntax='proto3',
serialized_pb=_b('\n\x0frsb_event.proto\x12\x03Rsh\"\xdc\x02\n\x05Point\x12$\n\x08\x63hannels\x18\x01 \x03(\x0b\x32\x12.Rsh.Point.Channel\x1a\xac\x02\n\x07\x43hannel\x12\n\n\x02id\x18\x01 \x01(\x04\x12(\n\x06\x62locks\x18\x02 \x03(\x0b\x32\x18.Rsh.Point.Channel.Block\x1a\xea\x01\n\x05\x42lock\x12\x0c\n\x04time\x18\x01 \x01(\x04\x12.\n\x06\x66rames\x18\x02 \x03(\x0b\x32\x1e.Rsh.Point.Channel.Block.Frame\x12/\n\x06\x65vents\x18\x03 \x01(\x0b\x32\x1f.Rsh.Point.Channel.Block.Events\x12\x0e\n\x06length\x18\x04 \x01(\x04\x12\x10\n\x08\x62in_size\x18\x05 \x01(\x04\x1a#\n\x05\x46rame\x12\x0c\n\x04time\x18\x01 \x01(\x04\x12\x0c\n\x04\x64\x61ta\x18\x02 \x01(\x0c\x1a+\n\x06\x45vents\x12\r\n\x05times\x18\x01 \x03(\x04\x12\x12\n\namplitudes\x18\x02 \x03(\x04\x62\x06proto3')
)
_POINT_CHANNEL_BLOCK_FRAME = _descriptor.Descriptor(
name='Frame',
full_name='Rsh.Point.Channel.Block.Frame',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='time', full_name='Rsh.Point.Channel.Block.Frame.time', index=0,
number=1, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='data', full_name='Rsh.Point.Channel.Block.Frame.data', index=1,
number=2, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=293,
serialized_end=328,
)
_POINT_CHANNEL_BLOCK_EVENTS = _descriptor.Descriptor(
name='Events',
full_name='Rsh.Point.Channel.Block.Events',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='times', full_name='Rsh.Point.Channel.Block.Events.times', index=0,
number=1, type=4, cpp_type=4, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='amplitudes', full_name='Rsh.Point.Channel.Block.Events.amplitudes', index=1,
number=2, type=4, cpp_type=4, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=330,
serialized_end=373,
)
_POINT_CHANNEL_BLOCK = _descriptor.Descriptor(
name='Block',
full_name='Rsh.Point.Channel.Block',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='time', full_name='Rsh.Point.Channel.Block.time', index=0,
number=1, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='frames', full_name='Rsh.Point.Channel.Block.frames', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='events', full_name='Rsh.Point.Channel.Block.events', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='length', full_name='Rsh.Point.Channel.Block.length', index=3,
number=4, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='bin_size', full_name='Rsh.Point.Channel.Block.bin_size', index=4,
number=5, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_POINT_CHANNEL_BLOCK_FRAME, _POINT_CHANNEL_BLOCK_EVENTS, ],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=139,
serialized_end=373,
)
_POINT_CHANNEL = _descriptor.Descriptor(
name='Channel',
full_name='Rsh.Point.Channel',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='id', full_name='Rsh.Point.Channel.id', index=0,
number=1, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='blocks', full_name='Rsh.Point.Channel.blocks', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_POINT_CHANNEL_BLOCK, ],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=73,
serialized_end=373,
)
_POINT = _descriptor.Descriptor(
name='Point',
full_name='Rsh.Point',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='channels', full_name='Rsh.Point.channels', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_POINT_CHANNEL, ],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=25,
serialized_end=373,
)
_POINT_CHANNEL_BLOCK_FRAME.containing_type = _POINT_CHANNEL_BLOCK
_POINT_CHANNEL_BLOCK_EVENTS.containing_type = _POINT_CHANNEL_BLOCK
_POINT_CHANNEL_BLOCK.fields_by_name['frames'].message_type = _POINT_CHANNEL_BLOCK_FRAME
_POINT_CHANNEL_BLOCK.fields_by_name['events'].message_type = _POINT_CHANNEL_BLOCK_EVENTS
_POINT_CHANNEL_BLOCK.containing_type = _POINT_CHANNEL
_POINT_CHANNEL.fields_by_name['blocks'].message_type = _POINT_CHANNEL_BLOCK
_POINT_CHANNEL.containing_type = _POINT
_POINT.fields_by_name['channels'].message_type = _POINT_CHANNEL
DESCRIPTOR.message_types_by_name['Point'] = _POINT
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Point = _reflection.GeneratedProtocolMessageType('Point', (_message.Message,), dict(
Channel = _reflection.GeneratedProtocolMessageType('Channel', (_message.Message,), dict(
Block = _reflection.GeneratedProtocolMessageType('Block', (_message.Message,), dict(
Frame = _reflection.GeneratedProtocolMessageType('Frame', (_message.Message,), dict(
DESCRIPTOR = _POINT_CHANNEL_BLOCK_FRAME,
__module__ = 'rsb_event_pb2'
# @@protoc_insertion_point(class_scope:Rsh.Point.Channel.Block.Frame)
))
,
Events = _reflection.GeneratedProtocolMessageType('Events', (_message.Message,), dict(
DESCRIPTOR = _POINT_CHANNEL_BLOCK_EVENTS,
__module__ = 'rsb_event_pb2'
# @@protoc_insertion_point(class_scope:Rsh.Point.Channel.Block.Events)
))
,
DESCRIPTOR = _POINT_CHANNEL_BLOCK,
__module__ = 'rsb_event_pb2'
# @@protoc_insertion_point(class_scope:Rsh.Point.Channel.Block)
))
,
DESCRIPTOR = _POINT_CHANNEL,
__module__ = 'rsb_event_pb2'
# @@protoc_insertion_point(class_scope:Rsh.Point.Channel)
))
,
DESCRIPTOR = _POINT,
__module__ = 'rsb_event_pb2'
# @@protoc_insertion_point(class_scope:Rsh.Point)
))
_sym_db.RegisterMessage(Point)
_sym_db.RegisterMessage(Point.Channel)
_sym_db.RegisterMessage(Point.Channel.Block)
_sym_db.RegisterMessage(Point.Channel.Block.Frame)
_sym_db.RegisterMessage(Point.Channel.Block.Events)
# @@protoc_insertion_point(module_scope) | dfparser/rsb_event_pb2.py |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='rsb_event.proto',
package='Rsh',
syntax='proto3',
serialized_pb=_b('\n\x0frsb_event.proto\x12\x03Rsh\"\xdc\x02\n\x05Point\x12$\n\x08\x63hannels\x18\x01 \x03(\x0b\x32\x12.Rsh.Point.Channel\x1a\xac\x02\n\x07\x43hannel\x12\n\n\x02id\x18\x01 \x01(\x04\x12(\n\x06\x62locks\x18\x02 \x03(\x0b\x32\x18.Rsh.Point.Channel.Block\x1a\xea\x01\n\x05\x42lock\x12\x0c\n\x04time\x18\x01 \x01(\x04\x12.\n\x06\x66rames\x18\x02 \x03(\x0b\x32\x1e.Rsh.Point.Channel.Block.Frame\x12/\n\x06\x65vents\x18\x03 \x01(\x0b\x32\x1f.Rsh.Point.Channel.Block.Events\x12\x0e\n\x06length\x18\x04 \x01(\x04\x12\x10\n\x08\x62in_size\x18\x05 \x01(\x04\x1a#\n\x05\x46rame\x12\x0c\n\x04time\x18\x01 \x01(\x04\x12\x0c\n\x04\x64\x61ta\x18\x02 \x01(\x0c\x1a+\n\x06\x45vents\x12\r\n\x05times\x18\x01 \x03(\x04\x12\x12\n\namplitudes\x18\x02 \x03(\x04\x62\x06proto3')
)
_POINT_CHANNEL_BLOCK_FRAME = _descriptor.Descriptor(
name='Frame',
full_name='Rsh.Point.Channel.Block.Frame',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='time', full_name='Rsh.Point.Channel.Block.Frame.time', index=0,
number=1, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='data', full_name='Rsh.Point.Channel.Block.Frame.data', index=1,
number=2, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=293,
serialized_end=328,
)
_POINT_CHANNEL_BLOCK_EVENTS = _descriptor.Descriptor(
name='Events',
full_name='Rsh.Point.Channel.Block.Events',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='times', full_name='Rsh.Point.Channel.Block.Events.times', index=0,
number=1, type=4, cpp_type=4, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='amplitudes', full_name='Rsh.Point.Channel.Block.Events.amplitudes', index=1,
number=2, type=4, cpp_type=4, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=330,
serialized_end=373,
)
_POINT_CHANNEL_BLOCK = _descriptor.Descriptor(
name='Block',
full_name='Rsh.Point.Channel.Block',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='time', full_name='Rsh.Point.Channel.Block.time', index=0,
number=1, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='frames', full_name='Rsh.Point.Channel.Block.frames', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='events', full_name='Rsh.Point.Channel.Block.events', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='length', full_name='Rsh.Point.Channel.Block.length', index=3,
number=4, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='bin_size', full_name='Rsh.Point.Channel.Block.bin_size', index=4,
number=5, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_POINT_CHANNEL_BLOCK_FRAME, _POINT_CHANNEL_BLOCK_EVENTS, ],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=139,
serialized_end=373,
)
_POINT_CHANNEL = _descriptor.Descriptor(
name='Channel',
full_name='Rsh.Point.Channel',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='id', full_name='Rsh.Point.Channel.id', index=0,
number=1, type=4, cpp_type=4, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='blocks', full_name='Rsh.Point.Channel.blocks', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_POINT_CHANNEL_BLOCK, ],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=73,
serialized_end=373,
)
_POINT = _descriptor.Descriptor(
name='Point',
full_name='Rsh.Point',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='channels', full_name='Rsh.Point.channels', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_POINT_CHANNEL, ],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=25,
serialized_end=373,
)
_POINT_CHANNEL_BLOCK_FRAME.containing_type = _POINT_CHANNEL_BLOCK
_POINT_CHANNEL_BLOCK_EVENTS.containing_type = _POINT_CHANNEL_BLOCK
_POINT_CHANNEL_BLOCK.fields_by_name['frames'].message_type = _POINT_CHANNEL_BLOCK_FRAME
_POINT_CHANNEL_BLOCK.fields_by_name['events'].message_type = _POINT_CHANNEL_BLOCK_EVENTS
_POINT_CHANNEL_BLOCK.containing_type = _POINT_CHANNEL
_POINT_CHANNEL.fields_by_name['blocks'].message_type = _POINT_CHANNEL_BLOCK
_POINT_CHANNEL.containing_type = _POINT
_POINT.fields_by_name['channels'].message_type = _POINT_CHANNEL
DESCRIPTOR.message_types_by_name['Point'] = _POINT
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Point = _reflection.GeneratedProtocolMessageType('Point', (_message.Message,), dict(
Channel = _reflection.GeneratedProtocolMessageType('Channel', (_message.Message,), dict(
Block = _reflection.GeneratedProtocolMessageType('Block', (_message.Message,), dict(
Frame = _reflection.GeneratedProtocolMessageType('Frame', (_message.Message,), dict(
DESCRIPTOR = _POINT_CHANNEL_BLOCK_FRAME,
__module__ = 'rsb_event_pb2'
# @@protoc_insertion_point(class_scope:Rsh.Point.Channel.Block.Frame)
))
,
Events = _reflection.GeneratedProtocolMessageType('Events', (_message.Message,), dict(
DESCRIPTOR = _POINT_CHANNEL_BLOCK_EVENTS,
__module__ = 'rsb_event_pb2'
# @@protoc_insertion_point(class_scope:Rsh.Point.Channel.Block.Events)
))
,
DESCRIPTOR = _POINT_CHANNEL_BLOCK,
__module__ = 'rsb_event_pb2'
# @@protoc_insertion_point(class_scope:Rsh.Point.Channel.Block)
))
,
DESCRIPTOR = _POINT_CHANNEL,
__module__ = 'rsb_event_pb2'
# @@protoc_insertion_point(class_scope:Rsh.Point.Channel)
))
,
DESCRIPTOR = _POINT,
__module__ = 'rsb_event_pb2'
# @@protoc_insertion_point(class_scope:Rsh.Point)
))
_sym_db.RegisterMessage(Point)
_sym_db.RegisterMessage(Point.Channel)
_sym_db.RegisterMessage(Point.Channel.Block)
_sym_db.RegisterMessage(Point.Channel.Block.Frame)
_sym_db.RegisterMessage(Point.Channel.Block.Events)
# @@protoc_insertion_point(module_scope) | 0.261048 | 0.15444 |
from os import path
import json
import datetime
from coinoxr.response import Response
from coinoxr.client import HttpClient
from urllib.parse import urlparse
class StubHttpClient(HttpClient):
def __init__(self):
self._app_ids = []
self._dates = []
def get(self, url, params):
route = urlparse(url).path.split("/")
filename = route[-1].replace(".json", "")
amount = None
from_currency = None
to_currency = None
if "convert" in route:
filename = "convert"
amount = route[-3]
from_currency = route[-2]
to_currency = route[-1]
file_path = "tests/fixtures/%s.json" % filename
if not path.isfile(file_path) and "historical" not in route:
return Response(404, None)
if "ohlc.json" in route and not self.valid_start_time(params["start_time"]):
response = self.json("tests/fixtures/invalid_start_time.json")
return Response(response["code"], response["content"])
if "ohlc.json" in route and not self.valid_start_point(params["period"]):
response = self.json("tests/fixtures/invalid_period_start_point.json")
return Response(response["code"], response["content"])
if "historical" in route and not self.valid_date(filename):
response = self.json("tests/fixtures/invalid_date.json")
return Response(response["code"], response["content"])
if "historical" in route and self.missing_date(filename):
response = self.json("tests/fixtures/date_not_available.json")
return Response(response["code"], response["content"])
if filename in ["time-series"] and not self.valid_range(params):
response = self.json("tests/fixtures/invalid_date_range.json")
return Response(response["code"], response["content"])
if filename in ["time-series"] and not self.range_available(params):
response = self.json("tests/fixtures/range_not_available.json")
return Response(response["code"], response["content"])
if filename not in ["currencies"] and not self.valid_app_id(params):
response = self.json("tests/fixtures/invalid_app_id.json")
return Response(response["code"], response["content"])
if filename not in ["currencies"] and self.missing_app_id(params):
response = self.json("tests/fixtures/missing_app_id.json")
return Response(response["code"], response["content"])
if not self.valid_conversion(from_currency, to_currency):
response = self.json("tests/fixtures/invalid_currency.json")
return Response(response["code"], response["content"])
if amount is not None and int(amount) < 0:
response = self.json("tests/fixtures/invalid_amount.json")
return Response(response["code"], response["content"])
response = self.json(file_path)
return Response(response["code"], response["content"])
def add_app_id(self, app_id):
self._app_ids.append(app_id)
def add_date(self, date):
self._dates.append(date)
def missing_app_id(self, params):
return params["app_id"] not in self._app_ids
def missing_date(self, date):
return date not in self._dates
def range_available(self, params):
return not self.missing_date(params["start"]) and not self.missing_date(
params["end"]
)
@classmethod
def valid_range(cls, params):
return cls.valid_date(params["start"]) and cls.valid_date(params["end"])
@classmethod
def valid_conversion(cls, from_currency, to_currency):
return cls.valid_currency(from_currency) and cls.valid_currency(to_currency)
@classmethod
def valid_currency(cls, currency):
return currency is None or len(currency) == 3
@classmethod
def valid_start_time(cls, start_time):
return cls.valid_datetime(start_time)
@classmethod
def valid_start_point(cls, period):
return period in ["30m"]
@classmethod
def valid_app_id(cls, params):
return len(params["app_id"]) > 3
@classmethod
def valid_date(cls, date):
try:
datetime.datetime.strptime(date, "%Y-%m-%d")
return True
except ValueError:
pass
return False
@classmethod
def valid_datetime(cls, date):
try:
datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S%z")
return True
except ValueError:
pass
return False
@staticmethod
def json(file):
content = None
with open(file) as f:
content = json.load(f)
return content | tests/stub_client.py | from os import path
import json
import datetime
from coinoxr.response import Response
from coinoxr.client import HttpClient
from urllib.parse import urlparse
class StubHttpClient(HttpClient):
def __init__(self):
self._app_ids = []
self._dates = []
def get(self, url, params):
route = urlparse(url).path.split("/")
filename = route[-1].replace(".json", "")
amount = None
from_currency = None
to_currency = None
if "convert" in route:
filename = "convert"
amount = route[-3]
from_currency = route[-2]
to_currency = route[-1]
file_path = "tests/fixtures/%s.json" % filename
if not path.isfile(file_path) and "historical" not in route:
return Response(404, None)
if "ohlc.json" in route and not self.valid_start_time(params["start_time"]):
response = self.json("tests/fixtures/invalid_start_time.json")
return Response(response["code"], response["content"])
if "ohlc.json" in route and not self.valid_start_point(params["period"]):
response = self.json("tests/fixtures/invalid_period_start_point.json")
return Response(response["code"], response["content"])
if "historical" in route and not self.valid_date(filename):
response = self.json("tests/fixtures/invalid_date.json")
return Response(response["code"], response["content"])
if "historical" in route and self.missing_date(filename):
response = self.json("tests/fixtures/date_not_available.json")
return Response(response["code"], response["content"])
if filename in ["time-series"] and not self.valid_range(params):
response = self.json("tests/fixtures/invalid_date_range.json")
return Response(response["code"], response["content"])
if filename in ["time-series"] and not self.range_available(params):
response = self.json("tests/fixtures/range_not_available.json")
return Response(response["code"], response["content"])
if filename not in ["currencies"] and not self.valid_app_id(params):
response = self.json("tests/fixtures/invalid_app_id.json")
return Response(response["code"], response["content"])
if filename not in ["currencies"] and self.missing_app_id(params):
response = self.json("tests/fixtures/missing_app_id.json")
return Response(response["code"], response["content"])
if not self.valid_conversion(from_currency, to_currency):
response = self.json("tests/fixtures/invalid_currency.json")
return Response(response["code"], response["content"])
if amount is not None and int(amount) < 0:
response = self.json("tests/fixtures/invalid_amount.json")
return Response(response["code"], response["content"])
response = self.json(file_path)
return Response(response["code"], response["content"])
def add_app_id(self, app_id):
self._app_ids.append(app_id)
def add_date(self, date):
self._dates.append(date)
def missing_app_id(self, params):
return params["app_id"] not in self._app_ids
def missing_date(self, date):
return date not in self._dates
def range_available(self, params):
return not self.missing_date(params["start"]) and not self.missing_date(
params["end"]
)
@classmethod
def valid_range(cls, params):
return cls.valid_date(params["start"]) and cls.valid_date(params["end"])
@classmethod
def valid_conversion(cls, from_currency, to_currency):
return cls.valid_currency(from_currency) and cls.valid_currency(to_currency)
@classmethod
def valid_currency(cls, currency):
return currency is None or len(currency) == 3
@classmethod
def valid_start_time(cls, start_time):
return cls.valid_datetime(start_time)
@classmethod
def valid_start_point(cls, period):
return period in ["30m"]
@classmethod
def valid_app_id(cls, params):
return len(params["app_id"]) > 3
@classmethod
def valid_date(cls, date):
try:
datetime.datetime.strptime(date, "%Y-%m-%d")
return True
except ValueError:
pass
return False
@classmethod
def valid_datetime(cls, date):
try:
datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S%z")
return True
except ValueError:
pass
return False
@staticmethod
def json(file):
content = None
with open(file) as f:
content = json.load(f)
return content | 0.473414 | 0.075892 |
""" utils/test/test_utils """
import unittest
import numpy as np
from sklearn.preprocessing import normalize, StandardScaler, MinMaxScaler
from ilcksvd.utils.utils import Normalizer
class Test_Normalizer(unittest.TestCase):
def setUp(self):
samples = 3
features = 5
self.data = np.random.rand(samples, features)
def test_none(self):
self.assertTrue(np.array_equal(
self.data,
Normalizer.none(self.data)
))
def test_l1_norm(self):
self.assertTrue(np.array_equal(
normalize(self.data, 'l1'),
Normalizer.l1_norm(self.data)
))
def test_l2_norm(self):
self.assertTrue(np.array_equal(
normalize(self.data, 'l2'),
Normalizer.l2_norm(self.data)
))
def test_max_norm(self):
self.assertTrue(np.array_equal(
normalize(self.data, 'max'),
Normalizer.max_norm(self.data)
))
def test_standardize(self):
self.assertTrue(np.array_equal(
StandardScaler().fit_transform(self.data),
Normalizer.standardize(self.data)[1]
))
def test_standardize_with_scaler(self):
scaler = StandardScaler()
scaler.fit(self.data)
self.assertTrue(np.array_equal(
scaler.transform(self.data),
Normalizer.standardize(self.data, scaler)[1]
))
self.assertEqual(scaler, Normalizer.standardize(self.data, scaler)[0])
def test_normalize(self):
self.assertTrue(np.array_equal(
MinMaxScaler().fit_transform(self.data),
Normalizer.normalize(self.data)[1]
))
def test_normalize_with_scaler(self):
scaler = MinMaxScaler()
scaler.fit(self.data)
self.assertTrue(np.array_equal(
scaler.transform(self.data),
Normalizer.normalize(self.data, scaler)[1]
))
self.assertEqual(scaler, Normalizer.normalize(self.data, scaler)[0])
def test_get_normalizer_none(self):
self.assertTrue(np.array_equal(
Normalizer.none(self.data),
Normalizer.get_normalizer(Normalizer.NONE, data=self.data)
))
def test_get_normalizer_l1_norm(self):
self.assertTrue(np.array_equal(
Normalizer.l1_norm(self.data),
Normalizer.get_normalizer(Normalizer.L1_NORM, data=self.data)
))
def test_get_normalizer_l2_norm(self):
self.assertTrue(np.array_equal(
Normalizer.l2_norm(self.data),
Normalizer.get_normalizer(Normalizer.L2_NORM, data=self.data)
))
def test_get_normalizer_max_norm(self):
self.assertTrue(np.array_equal(
Normalizer.max_norm(self.data),
Normalizer.get_normalizer(Normalizer.MAX_NORM, data=self.data)
))
def test_get_normalizer_standardize(self):
self.assertTrue(np.array_equal(
Normalizer.standardize(self.data)[1],
Normalizer.get_normalizer(Normalizer.STANDARDIZE, data=self.data)[1]
))
def test_get_normalizer_standardize_with_scaler(self):
scaler = StandardScaler()
scaler.fit(self.data)
self.assertTrue(np.array_equal(
Normalizer.standardize(self.data, fitted_scaler=scaler)[1],
Normalizer.get_normalizer(Normalizer.STANDARDIZE, data=self.data, fitted_scaler=scaler)[1]
))
self.assertTrue(
Normalizer.standardize(self.data, fitted_scaler=scaler)[0],
Normalizer.get_normalizer(Normalizer.STANDARDIZE, data=self.data, fitted_scaler=scaler)[0]
)
def test_get_normalizer_normalize(self):
self.assertTrue(np.array_equal(
Normalizer.normalize(self.data)[1],
Normalizer.get_normalizer(Normalizer.NORMALIZE, data=self.data)[1]
))
def test_get_normalizer_normalize_with_scaler(self):
scaler = MinMaxScaler()
scaler.fit(self.data)
self.assertTrue(np.array_equal(
Normalizer.normalize(self.data, fitted_scaler=scaler)[1],
Normalizer.get_normalizer(Normalizer.NORMALIZE, data=self.data, fitted_scaler=scaler)[1]
))
self.assertTrue(
Normalizer.normalize(self.data, fitted_scaler=scaler)[0],
Normalizer.get_normalizer(Normalizer.NORMALIZE, data=self.data, fitted_scaler=scaler)[0]
)
def test_functor(self):
self.assertTrue(np.array_equal(
Normalizer.l1_norm(self.data),
Normalizer()(Normalizer.L1_NORM, data=self.data)
))
if __name__ == '__main__':
unittest.main() | ilcksvd/utils/test/test_utils.py | """ utils/test/test_utils """
import unittest
import numpy as np
from sklearn.preprocessing import normalize, StandardScaler, MinMaxScaler
from ilcksvd.utils.utils import Normalizer
class Test_Normalizer(unittest.TestCase):
def setUp(self):
samples = 3
features = 5
self.data = np.random.rand(samples, features)
def test_none(self):
self.assertTrue(np.array_equal(
self.data,
Normalizer.none(self.data)
))
def test_l1_norm(self):
self.assertTrue(np.array_equal(
normalize(self.data, 'l1'),
Normalizer.l1_norm(self.data)
))
def test_l2_norm(self):
self.assertTrue(np.array_equal(
normalize(self.data, 'l2'),
Normalizer.l2_norm(self.data)
))
def test_max_norm(self):
self.assertTrue(np.array_equal(
normalize(self.data, 'max'),
Normalizer.max_norm(self.data)
))
def test_standardize(self):
self.assertTrue(np.array_equal(
StandardScaler().fit_transform(self.data),
Normalizer.standardize(self.data)[1]
))
def test_standardize_with_scaler(self):
scaler = StandardScaler()
scaler.fit(self.data)
self.assertTrue(np.array_equal(
scaler.transform(self.data),
Normalizer.standardize(self.data, scaler)[1]
))
self.assertEqual(scaler, Normalizer.standardize(self.data, scaler)[0])
def test_normalize(self):
self.assertTrue(np.array_equal(
MinMaxScaler().fit_transform(self.data),
Normalizer.normalize(self.data)[1]
))
def test_normalize_with_scaler(self):
scaler = MinMaxScaler()
scaler.fit(self.data)
self.assertTrue(np.array_equal(
scaler.transform(self.data),
Normalizer.normalize(self.data, scaler)[1]
))
self.assertEqual(scaler, Normalizer.normalize(self.data, scaler)[0])
def test_get_normalizer_none(self):
self.assertTrue(np.array_equal(
Normalizer.none(self.data),
Normalizer.get_normalizer(Normalizer.NONE, data=self.data)
))
def test_get_normalizer_l1_norm(self):
self.assertTrue(np.array_equal(
Normalizer.l1_norm(self.data),
Normalizer.get_normalizer(Normalizer.L1_NORM, data=self.data)
))
def test_get_normalizer_l2_norm(self):
self.assertTrue(np.array_equal(
Normalizer.l2_norm(self.data),
Normalizer.get_normalizer(Normalizer.L2_NORM, data=self.data)
))
def test_get_normalizer_max_norm(self):
self.assertTrue(np.array_equal(
Normalizer.max_norm(self.data),
Normalizer.get_normalizer(Normalizer.MAX_NORM, data=self.data)
))
def test_get_normalizer_standardize(self):
self.assertTrue(np.array_equal(
Normalizer.standardize(self.data)[1],
Normalizer.get_normalizer(Normalizer.STANDARDIZE, data=self.data)[1]
))
def test_get_normalizer_standardize_with_scaler(self):
scaler = StandardScaler()
scaler.fit(self.data)
self.assertTrue(np.array_equal(
Normalizer.standardize(self.data, fitted_scaler=scaler)[1],
Normalizer.get_normalizer(Normalizer.STANDARDIZE, data=self.data, fitted_scaler=scaler)[1]
))
self.assertTrue(
Normalizer.standardize(self.data, fitted_scaler=scaler)[0],
Normalizer.get_normalizer(Normalizer.STANDARDIZE, data=self.data, fitted_scaler=scaler)[0]
)
def test_get_normalizer_normalize(self):
self.assertTrue(np.array_equal(
Normalizer.normalize(self.data)[1],
Normalizer.get_normalizer(Normalizer.NORMALIZE, data=self.data)[1]
))
def test_get_normalizer_normalize_with_scaler(self):
scaler = MinMaxScaler()
scaler.fit(self.data)
self.assertTrue(np.array_equal(
Normalizer.normalize(self.data, fitted_scaler=scaler)[1],
Normalizer.get_normalizer(Normalizer.NORMALIZE, data=self.data, fitted_scaler=scaler)[1]
))
self.assertTrue(
Normalizer.normalize(self.data, fitted_scaler=scaler)[0],
Normalizer.get_normalizer(Normalizer.NORMALIZE, data=self.data, fitted_scaler=scaler)[0]
)
def test_functor(self):
self.assertTrue(np.array_equal(
Normalizer.l1_norm(self.data),
Normalizer()(Normalizer.L1_NORM, data=self.data)
))
if __name__ == '__main__':
unittest.main() | 0.802981 | 0.721541 |
def PCG_128BIT_CONSTANT(high, low):
''' Some members of the PCG library use 128-bit math.
This is not a problem for Python at all. But still provide this
method of constructing literals, for compatibility.
'''
return high << 64 | low
# C++ iostreams don't exist. Instead, the Engine class supports __reduce__.
def unxorshift(x, bits, shift):
''' XorShifts are invertable, but they are someting of a pain to invert.
This function backs them out. It's used by the whacky "inside out"
generator defined later.
'''
itype = type(x)
if 2*shift >= bits:
return x ^ (x >> shift)
lowmask1 = (itype.ONE << (bits - shift*2)) - 1
highmask1 = ~lowmask1
top1 = x
bottom1 = x & lowmask1
top1 ^= top1 >> shift
top1 &= highmask1
x = top1 | bottom1
lowmask2 = (itype.ONE << (bits - shift)) - 1
bottom2 = x & lowmask2
bottom2 = unxorshift(bottom2, bits - shift, shift)
bottom2 &= lowmask1
return top1 | bottom2
# rotl and rotr are implemented on the ints.* classes
# C++-style seed sequences don't exist. Instead, the seed must always be
# a bytestring of appropriate length, or defaults to urandom.
def bounded_rand(rng, upper_bound):
if not 0 < upper_bound:
raise ValueError('Bound must be positive!')
if not upper_bound <= rng.MAX:
# TODO: remove this limitation (not possible in C++ :P)
raise ValueError('Bound must (currently) fit in result size!')
rtype = type(rng.MAX)
assert rng.MAX == rtype.MAX
threshold = (rtype.MOD - upper_bound) % upper_bound
while True:
r = rng()
if r >= threshold:
return int(r) % upper_bound
def shuffle(arr, rng):
count = len(arr)
while count > 1:
chosen = bounded_rand(rng, count)
count -= 1
arr[chosen], arr[count] = arr[count], arr[chosen]
# static_arbitrary_seed appears to be used by *nobody* at all,
# and what would it even mean in Python?
# printable_typename is unneeded in Python, repr() does a good job already. | pcg_random/pcg_extras.py | def PCG_128BIT_CONSTANT(high, low):
''' Some members of the PCG library use 128-bit math.
This is not a problem for Python at all. But still provide this
method of constructing literals, for compatibility.
'''
return high << 64 | low
# C++ iostreams don't exist. Instead, the Engine class supports __reduce__.
def unxorshift(x, bits, shift):
''' XorShifts are invertable, but they are someting of a pain to invert.
This function backs them out. It's used by the whacky "inside out"
generator defined later.
'''
itype = type(x)
if 2*shift >= bits:
return x ^ (x >> shift)
lowmask1 = (itype.ONE << (bits - shift*2)) - 1
highmask1 = ~lowmask1
top1 = x
bottom1 = x & lowmask1
top1 ^= top1 >> shift
top1 &= highmask1
x = top1 | bottom1
lowmask2 = (itype.ONE << (bits - shift)) - 1
bottom2 = x & lowmask2
bottom2 = unxorshift(bottom2, bits - shift, shift)
bottom2 &= lowmask1
return top1 | bottom2
# rotl and rotr are implemented on the ints.* classes
# C++-style seed sequences don't exist. Instead, the seed must always be
# a bytestring of appropriate length, or defaults to urandom.
def bounded_rand(rng, upper_bound):
if not 0 < upper_bound:
raise ValueError('Bound must be positive!')
if not upper_bound <= rng.MAX:
# TODO: remove this limitation (not possible in C++ :P)
raise ValueError('Bound must (currently) fit in result size!')
rtype = type(rng.MAX)
assert rng.MAX == rtype.MAX
threshold = (rtype.MOD - upper_bound) % upper_bound
while True:
r = rng()
if r >= threshold:
return int(r) % upper_bound
def shuffle(arr, rng):
count = len(arr)
while count > 1:
chosen = bounded_rand(rng, count)
count -= 1
arr[chosen], arr[count] = arr[count], arr[chosen]
# static_arbitrary_seed appears to be used by *nobody* at all,
# and what would it even mean in Python?
# printable_typename is unneeded in Python, repr() does a good job already. | 0.523177 | 0.502747 |
import enum
import math
from multimethod import multimethod
def parse_unit(str_unit: str):
for u in Unit:
if str_unit == u.name:
return u
if str_unit == "KiB":
return Unit.KibiByte
elif str_unit in ["4KiB blocks", "4KiB Blocks"]:
return Unit.Blocks4096
elif str_unit == "MiB":
return Unit.MebiByte
elif str_unit == "GiB":
return Unit.GibiByte
elif str_unit == "TiB":
return Unit.TebiByte
if str_unit == "B":
return Unit.Byte
elif str_unit == "KB":
return Unit.KiloByte
elif str_unit == "MB":
return Unit.MegaByte
elif str_unit == "GB":
return Unit.GigaByte
elif str_unit == "TB":
return Unit.TeraByte
raise ValueError(f"Unable to parse {str_unit}")
class Unit(enum.Enum):
Byte = 1
KiloByte = 1000
KibiByte = 1024
MegaByte = 1000 * KiloByte
MebiByte = 1024 * KibiByte
GigaByte = 1000 * MegaByte
GibiByte = 1024 * MebiByte
TeraByte = 1000 * GigaByte
TebiByte = 1024 * GibiByte
Blocks512 = 512
Blocks4096 = 4096
KiB = KibiByte
KB = KiloByte
MiB = MebiByte
MB = MegaByte
GiB = GibiByte
GB = GigaByte
TiB = TebiByte
TB = TeraByte
def get_value(self):
return self.value
class UnitPerSecond:
def __init__(self, unit):
self.value = unit.get_value()
self.name = unit.name + "/s"
def get_value(self):
return self.value
class Size:
def __init__(self, value: float, unit: Unit = Unit.Byte):
if value < 0:
raise ValueError("Size has to be positive.")
self.value = value * unit.value
self.unit = unit
def __str__(self):
return f"{self.get_value(self.unit)} {self.unit.name}"
def __hash__(self):
return self.value.__hash__()
def __int__(self):
return int(self.get_value())
def __add__(self, other):
return Size(self.get_value() + other.get_value())
def __lt__(self, other):
return self.get_value() < other.get_value()
def __le__(self, other):
return self.get_value() <= other.get_value()
def __eq__(self, other):
return self.get_value() == other.get_value()
def __ne__(self, other):
return self.get_value() != other.get_value()
def __gt__(self, other):
return self.get_value() > other.get_value()
def __ge__(self, other):
return self.get_value() >= other.get_value()
def __sub__(self, other):
if self < other:
raise ValueError("Subtracted value is too big. Result size cannot be negative.")
return Size(self.get_value() - other.get_value())
@multimethod
def __mul__(self, other: int):
return Size(math.ceil(self.get_value() * other))
@multimethod
def __rmul__(self, other: int):
return Size(math.ceil(self.get_value() * other))
@multimethod
def __mul__(self, other: float):
return Size(math.ceil(self.get_value() * other))
@multimethod
def __rmul__(self, other: float):
return Size(math.ceil(self.get_value() * other))
@multimethod
def __truediv__(self, other):
if other.get_value() == 0:
raise ValueError("Divisor must not be equal to 0.")
return self.get_value() / other.get_value()
@multimethod
def __truediv__(self, other: int):
if other == 0:
raise ValueError("Divisor must not be equal to 0.")
return Size(math.ceil(self.get_value() / other))
def set_unit(self, new_unit: Unit):
new_size = Size(self.get_value(target_unit=new_unit), unit=new_unit)
if new_size != self:
raise ValueError(f"{new_unit} is not precise enough for {self}")
self.value = new_size.value
self.unit = new_size.unit
return self
def get_value(self, target_unit: Unit = Unit.Byte):
return self.value / target_unit.value
def is_zero(self):
if self.value == 0:
return True
else:
return False
def align_up(self, alignment):
if self == self.align_down(alignment):
return Size(int(self))
return Size(int(self.align_down(alignment)) + alignment)
def align_down(self, alignment):
if alignment <= 0:
raise ValueError("Alignment must be a positive value!")
if alignment & (alignment - 1):
raise ValueError("Alignment must be a power of two!")
return Size(int(self) & ~(alignment - 1))
@staticmethod
def zero():
return Size(0) | test/functional/test-framework/test_utils/size.py |
import enum
import math
from multimethod import multimethod
def parse_unit(str_unit: str):
for u in Unit:
if str_unit == u.name:
return u
if str_unit == "KiB":
return Unit.KibiByte
elif str_unit in ["4KiB blocks", "4KiB Blocks"]:
return Unit.Blocks4096
elif str_unit == "MiB":
return Unit.MebiByte
elif str_unit == "GiB":
return Unit.GibiByte
elif str_unit == "TiB":
return Unit.TebiByte
if str_unit == "B":
return Unit.Byte
elif str_unit == "KB":
return Unit.KiloByte
elif str_unit == "MB":
return Unit.MegaByte
elif str_unit == "GB":
return Unit.GigaByte
elif str_unit == "TB":
return Unit.TeraByte
raise ValueError(f"Unable to parse {str_unit}")
class Unit(enum.Enum):
Byte = 1
KiloByte = 1000
KibiByte = 1024
MegaByte = 1000 * KiloByte
MebiByte = 1024 * KibiByte
GigaByte = 1000 * MegaByte
GibiByte = 1024 * MebiByte
TeraByte = 1000 * GigaByte
TebiByte = 1024 * GibiByte
Blocks512 = 512
Blocks4096 = 4096
KiB = KibiByte
KB = KiloByte
MiB = MebiByte
MB = MegaByte
GiB = GibiByte
GB = GigaByte
TiB = TebiByte
TB = TeraByte
def get_value(self):
return self.value
class UnitPerSecond:
def __init__(self, unit):
self.value = unit.get_value()
self.name = unit.name + "/s"
def get_value(self):
return self.value
class Size:
def __init__(self, value: float, unit: Unit = Unit.Byte):
if value < 0:
raise ValueError("Size has to be positive.")
self.value = value * unit.value
self.unit = unit
def __str__(self):
return f"{self.get_value(self.unit)} {self.unit.name}"
def __hash__(self):
return self.value.__hash__()
def __int__(self):
return int(self.get_value())
def __add__(self, other):
return Size(self.get_value() + other.get_value())
def __lt__(self, other):
return self.get_value() < other.get_value()
def __le__(self, other):
return self.get_value() <= other.get_value()
def __eq__(self, other):
return self.get_value() == other.get_value()
def __ne__(self, other):
return self.get_value() != other.get_value()
def __gt__(self, other):
return self.get_value() > other.get_value()
def __ge__(self, other):
return self.get_value() >= other.get_value()
def __sub__(self, other):
if self < other:
raise ValueError("Subtracted value is too big. Result size cannot be negative.")
return Size(self.get_value() - other.get_value())
@multimethod
def __mul__(self, other: int):
return Size(math.ceil(self.get_value() * other))
@multimethod
def __rmul__(self, other: int):
return Size(math.ceil(self.get_value() * other))
@multimethod
def __mul__(self, other: float):
return Size(math.ceil(self.get_value() * other))
@multimethod
def __rmul__(self, other: float):
return Size(math.ceil(self.get_value() * other))
@multimethod
def __truediv__(self, other):
if other.get_value() == 0:
raise ValueError("Divisor must not be equal to 0.")
return self.get_value() / other.get_value()
@multimethod
def __truediv__(self, other: int):
if other == 0:
raise ValueError("Divisor must not be equal to 0.")
return Size(math.ceil(self.get_value() / other))
def set_unit(self, new_unit: Unit):
new_size = Size(self.get_value(target_unit=new_unit), unit=new_unit)
if new_size != self:
raise ValueError(f"{new_unit} is not precise enough for {self}")
self.value = new_size.value
self.unit = new_size.unit
return self
def get_value(self, target_unit: Unit = Unit.Byte):
return self.value / target_unit.value
def is_zero(self):
if self.value == 0:
return True
else:
return False
def align_up(self, alignment):
if self == self.align_down(alignment):
return Size(int(self))
return Size(int(self.align_down(alignment)) + alignment)
def align_down(self, alignment):
if alignment <= 0:
raise ValueError("Alignment must be a positive value!")
if alignment & (alignment - 1):
raise ValueError("Alignment must be a power of two!")
return Size(int(self) & ~(alignment - 1))
@staticmethod
def zero():
return Size(0) | 0.656768 | 0.403273 |
xs_gen = """\
set title "[CHAR] {reactor} Cross Section Generator"
set acelib "{xsdata}"
% --- Matrial Definitions ---
% Initial Fuel Stream
mat fuel -{fuel_density}
{fuel}
% Cladding Stream
mat cladding -{clad_density}
{cladding}
% Coolant Stream
mat coolant -{cool_density} moder lwtr 1001
{coolant}
therm lwtr lwj3.20t
% --- Run Specification ---
% Periodic boundary conditions
set bc 3
% Fuel universe
set gcu 100
% 1/8 square symmetry
{sym_flag}set sym 8
% Group Stucture
set egrid 5E-05 {group_lower_bound} {group_upper_bound}
set nfg {n_groups}
{group_inner_structure}
% Criticality calc
set pop {k_particles} {k_cycles} {k_cycles_skip}
% --- Geometry ---
pin 1
fill 100 {fuel_radius}
void {void_radius}
cladding {clad_radius}
coolant
pin 2
coolant
surf 100 inf
cell 110 100 fuel -100
lat 10 1 0.0 0.0 {lattice_xy} {lattice_xy} {cell_pitch}
{lattice}
surf 3000 sqc 0.0 0.0 {half_lattice_pitch}
cell 300 0 fill 10 -3000
cell 301 0 outside 3000
% --- Graphs ---
%plot 3 800 800
%mesh 3 800 800
% --- Group Constant Generation ---
% Energy group structure
ene energies 1
{group_structure}
% Total flux in {detector_mat}
det phi de energies dm {detector_mat}
% Group constant material
mat xsmat 1.0 {xsnuc} 1.0
% Set group transfer probability to this material
set gtpmat xsmat
% Specify the detectors
{xsdet}
"""
burnup = """\
set title "[CHAR] {reactor} Burnup Calculation"
set acelib "{xsdata}"
% --- Matrial Definitions ---
% Initial Fuel Stream
mat fuel -{fuel_density} burn {num_burn_regions}
{fuel}
% Cladding Stream
mat cladding -{clad_density}
{cladding}
% Coolant Stream
mat coolant -{cool_density} moder lwtr 1001
{coolant}
therm lwtr lwj3.20t
% --- Run Specification ---
% Periodic boundary conditions
set bc 3
% 1/8 square symmetry
{sym_flag}set sym 8
% Group Stucture
set egrid 5E-05 {group_lower_bound} {group_upper_bound}
set nfg {n_groups}
{group_inner_structure}
% Criticality calc
set pop {k_particles} {k_cycles} {k_cycles_skip}
% --- Geometry ---
pin 1
fuel {fuel_radius}
void {void_radius}
cladding {clad_radius}
coolant
pin 2
coolant
lat 10 1 0.0 0.0 {lattice_xy} {lattice_xy} {cell_pitch}
{lattice}
surf 3000 sqc 0.0 0.0 {half_lattice_pitch}
cell 300 0 fill 10 -3000
cell 301 0 outside 3000
% --- Graphs ---
%plot 3 800 800
%mesh 3 800 800
% Decay and fission yield libraries
set declib "{decay_lib}"
set nfylib "{fission_yield_lib}"
% Burnup calculation options
set bumode 2 % CRAM method
set pcc 1 % Predictor-corrector calculation on
set xscalc 2 % Calc cross sections from spectrum (fast)
set powdens {fuel_specific_power} % Fuel specific power [W/g]
% Depletion cycle
dep daytot
{depletion_times}
% Nuclide inventory
set inventory
{transmute_inventory}
""" | bright/xsgen/templates/lwr/serpent.py | xs_gen = """\
set title "[CHAR] {reactor} Cross Section Generator"
set acelib "{xsdata}"
% --- Matrial Definitions ---
% Initial Fuel Stream
mat fuel -{fuel_density}
{fuel}
% Cladding Stream
mat cladding -{clad_density}
{cladding}
% Coolant Stream
mat coolant -{cool_density} moder lwtr 1001
{coolant}
therm lwtr lwj3.20t
% --- Run Specification ---
% Periodic boundary conditions
set bc 3
% Fuel universe
set gcu 100
% 1/8 square symmetry
{sym_flag}set sym 8
% Group Stucture
set egrid 5E-05 {group_lower_bound} {group_upper_bound}
set nfg {n_groups}
{group_inner_structure}
% Criticality calc
set pop {k_particles} {k_cycles} {k_cycles_skip}
% --- Geometry ---
pin 1
fill 100 {fuel_radius}
void {void_radius}
cladding {clad_radius}
coolant
pin 2
coolant
surf 100 inf
cell 110 100 fuel -100
lat 10 1 0.0 0.0 {lattice_xy} {lattice_xy} {cell_pitch}
{lattice}
surf 3000 sqc 0.0 0.0 {half_lattice_pitch}
cell 300 0 fill 10 -3000
cell 301 0 outside 3000
% --- Graphs ---
%plot 3 800 800
%mesh 3 800 800
% --- Group Constant Generation ---
% Energy group structure
ene energies 1
{group_structure}
% Total flux in {detector_mat}
det phi de energies dm {detector_mat}
% Group constant material
mat xsmat 1.0 {xsnuc} 1.0
% Set group transfer probability to this material
set gtpmat xsmat
% Specify the detectors
{xsdet}
"""
burnup = """\
set title "[CHAR] {reactor} Burnup Calculation"
set acelib "{xsdata}"
% --- Matrial Definitions ---
% Initial Fuel Stream
mat fuel -{fuel_density} burn {num_burn_regions}
{fuel}
% Cladding Stream
mat cladding -{clad_density}
{cladding}
% Coolant Stream
mat coolant -{cool_density} moder lwtr 1001
{coolant}
therm lwtr lwj3.20t
% --- Run Specification ---
% Periodic boundary conditions
set bc 3
% 1/8 square symmetry
{sym_flag}set sym 8
% Group Stucture
set egrid 5E-05 {group_lower_bound} {group_upper_bound}
set nfg {n_groups}
{group_inner_structure}
% Criticality calc
set pop {k_particles} {k_cycles} {k_cycles_skip}
% --- Geometry ---
pin 1
fuel {fuel_radius}
void {void_radius}
cladding {clad_radius}
coolant
pin 2
coolant
lat 10 1 0.0 0.0 {lattice_xy} {lattice_xy} {cell_pitch}
{lattice}
surf 3000 sqc 0.0 0.0 {half_lattice_pitch}
cell 300 0 fill 10 -3000
cell 301 0 outside 3000
% --- Graphs ---
%plot 3 800 800
%mesh 3 800 800
% Decay and fission yield libraries
set declib "{decay_lib}"
set nfylib "{fission_yield_lib}"
% Burnup calculation options
set bumode 2 % CRAM method
set pcc 1 % Predictor-corrector calculation on
set xscalc 2 % Calc cross sections from spectrum (fast)
set powdens {fuel_specific_power} % Fuel specific power [W/g]
% Depletion cycle
dep daytot
{depletion_times}
% Nuclide inventory
set inventory
{transmute_inventory}
""" | 0.54359 | 0.343438 |
import valideer
from tornado.web import Application
from tornado.web import RequestHandler
from tornado.testing import AsyncHTTPTestCase
from tornwrap import validated
class Handler(RequestHandler):
@validated({"+name": valideer.Enum(("steve", "joe"))})
def get(self, arguments):
self.finish("Hello, %s!" % arguments.get('name', 'nobody'))
@validated(body={"name": valideer.Enum(("steve", "joe"))})
def post(self, body):
self.finish("Hello, %s!" % body.get('name', 'nobody'))
@validated(body=False, arguments=False)
def patch(self):
self.finish("Hello, World!")
@validated(arguments={"joe": "bool"}, body={"+name": valideer.Enum(("steve", "joe"))})
def put(self, arguments, body):
self.finish("Hello, %s!" % arguments.get('name', 'nobody'))
def _handle_request_exception(self, e):
if isinstance(e, valideer.ValidationError):
self.set_status(400)
self._reason = str(e)
self.write_error(400, reason=str(e))
else:
super(Handler, self)._handle_request_exception(e)
class Test(AsyncHTTPTestCase):
def get_app(self):
return Application([('/', Handler)])
def test_missing(self):
response = self.fetch("/")
self.assertEqual(response.code, 400)
def test_valid_urlparams(self):
response = self.fetch("/?name=steve")
self.assertEqual(response.code, 200)
self.assertEqual(response.body, "Hello, steve!")
def test_valid_body_args(self):
response = self.fetch("/?this=not+checked", method="POST", body="name=steve")
self.assertEqual(response.code, 200)
self.assertEqual(response.body, "Hello, steve!")
def test_no_body_args(self):
self.assertEqual(self.fetch("/?this=no", method="PATCH", body="").code, 400)
self.assertEqual(self.fetch("/", method="PATCH", body='{"no":0}').code, 400)
self.assertEqual(self.fetch("/", method="PATCH", body="").code, 200)
self.assertEqual(self.fetch("/?_=123456789", method="PATCH", body="").code, 200)
def test_invalid_body_args(self):
response = self.fetch("/", method="POST", body="name")
self.assertEqual(response.code, 400)
def test_ignore_empty(self):
response = self.fetch("/?joe=", method="POST", body="name=joe")
self.assertEqual(response.code, 200)
def test_valid_accepts(self):
response = self.fetch("/", method="POST", body="name=steve", headers={"Accept": "application/json"})
self.assertEqual(response.code, 200)
def test_extra_params(self):
response = self.fetch("/?joe=true", method="PUT", body="name=steve")
self.assertEqual(response.code, 200)
def test_valid_body_json(self):
response = self.fetch("/", method="POST", body='{"name": "joe"}')
self.assertEqual(response.code, 200)
self.assertEqual(response.body, "Hello, joe!")
def test_invalid(self):
response = self.fetch("/?name=andy")
self.assertEqual(response.code, 400)
def test_multiple(self):
response = self.fetch("/?name=steve&name=andy")
self.assertEqual(response.code, 400)
def test_initial_values(self):
self.assertRaises(ValueError, validated, arguments=True)
self.assertRaises(ValueError, validated, body=True) | tornwrap/tests/test_validated.py | import valideer
from tornado.web import Application
from tornado.web import RequestHandler
from tornado.testing import AsyncHTTPTestCase
from tornwrap import validated
class Handler(RequestHandler):
@validated({"+name": valideer.Enum(("steve", "joe"))})
def get(self, arguments):
self.finish("Hello, %s!" % arguments.get('name', 'nobody'))
@validated(body={"name": valideer.Enum(("steve", "joe"))})
def post(self, body):
self.finish("Hello, %s!" % body.get('name', 'nobody'))
@validated(body=False, arguments=False)
def patch(self):
self.finish("Hello, World!")
@validated(arguments={"joe": "bool"}, body={"+name": valideer.Enum(("steve", "joe"))})
def put(self, arguments, body):
self.finish("Hello, %s!" % arguments.get('name', 'nobody'))
def _handle_request_exception(self, e):
if isinstance(e, valideer.ValidationError):
self.set_status(400)
self._reason = str(e)
self.write_error(400, reason=str(e))
else:
super(Handler, self)._handle_request_exception(e)
class Test(AsyncHTTPTestCase):
def get_app(self):
return Application([('/', Handler)])
def test_missing(self):
response = self.fetch("/")
self.assertEqual(response.code, 400)
def test_valid_urlparams(self):
response = self.fetch("/?name=steve")
self.assertEqual(response.code, 200)
self.assertEqual(response.body, "Hello, steve!")
def test_valid_body_args(self):
response = self.fetch("/?this=not+checked", method="POST", body="name=steve")
self.assertEqual(response.code, 200)
self.assertEqual(response.body, "Hello, steve!")
def test_no_body_args(self):
self.assertEqual(self.fetch("/?this=no", method="PATCH", body="").code, 400)
self.assertEqual(self.fetch("/", method="PATCH", body='{"no":0}').code, 400)
self.assertEqual(self.fetch("/", method="PATCH", body="").code, 200)
self.assertEqual(self.fetch("/?_=123456789", method="PATCH", body="").code, 200)
def test_invalid_body_args(self):
response = self.fetch("/", method="POST", body="name")
self.assertEqual(response.code, 400)
def test_ignore_empty(self):
response = self.fetch("/?joe=", method="POST", body="name=joe")
self.assertEqual(response.code, 200)
def test_valid_accepts(self):
response = self.fetch("/", method="POST", body="name=steve", headers={"Accept": "application/json"})
self.assertEqual(response.code, 200)
def test_extra_params(self):
response = self.fetch("/?joe=true", method="PUT", body="name=steve")
self.assertEqual(response.code, 200)
def test_valid_body_json(self):
response = self.fetch("/", method="POST", body='{"name": "joe"}')
self.assertEqual(response.code, 200)
self.assertEqual(response.body, "Hello, joe!")
def test_invalid(self):
response = self.fetch("/?name=andy")
self.assertEqual(response.code, 400)
def test_multiple(self):
response = self.fetch("/?name=steve&name=andy")
self.assertEqual(response.code, 400)
def test_initial_values(self):
self.assertRaises(ValueError, validated, arguments=True)
self.assertRaises(ValueError, validated, body=True) | 0.581541 | 0.165054 |
import unittest
from modules.inventory.items.baseitems import StackableItem, NonStackableItem
characteristic = "An Example of a stackable item!"
asset = "path/to/asset"
class ExampleStackable(StackableItem):
@property
def characteristic(self):
return characteristic
@property
def asset(self):
return asset
class ExampleNonStackable(NonStackableItem):
@property
def characteristic(self):
return characteristic
@property
def asset(self):
return asset
class TestStackableItems(unittest.TestCase):
def setUp(self):
self.item = ExampleStackable()
def test_item_defaults(self):
self.assertEqual(self.item.count, 1)
self.assertEqual(self.item.characteristic, characteristic)
self.assertEqual(self.item.asset, asset)
def test_add_item(self):
self.item + 1
self.assertEqual(self.item.count, 2, msg="Add one item")
self.item + 10
self.assertEqual(self.item.count, 12, msg="Add multiple items")
def test_subtract_item(self):
self.item.count = 4
self.item - 1
self.assertEqual(self.item.count, 3, msg="Subtract 1 item")
self.item - 2
self.assertEqual(self.item.count, 1, msg="Subtract multiple items")
def test_negative_subtract(self):
with self.assertRaises(ValueError):
self.item - 1
self.assertEqual(self.item.count, 1)
def test_assign_count(self):
self.item.count = 100
self.assertEqual(self.item.count, 100)
self.item.count = 1
def test_negative_assign(self):
with self.assertRaises(ValueError):
self.item.count = 0
with self.assertRaises(ValueError):
self.item.count = -100
self.assertEqual(self.item.count, 1)
class TestNonStackableItem(unittest.TestCase):
def setUp(self):
self.item = ExampleNonStackable()
def test_item_defaults(self):
self.assertEqual(self.item.count, 1)
self.assertEqual(self.item.characteristic, characteristic)
self.assertEqual(self.item.asset, asset)
def test_add_item(self):
with self.assertRaises(ValueError):
self.item + 1
def test_subtract_item(self):
with self.assertRaises(ValueError):
self.item - 1
if __name__ == '__main__':
item_suite = unittest.TestSuite()
item_suite.addTest(TestNonStackableItem())
item_suite.addTest(TestStackableItems())
runner = unittest.TextTestRunner()
runner.run(item_suite) | romantic-revolutionaries/test/test_items.py | import unittest
from modules.inventory.items.baseitems import StackableItem, NonStackableItem
characteristic = "An Example of a stackable item!"
asset = "path/to/asset"
class ExampleStackable(StackableItem):
@property
def characteristic(self):
return characteristic
@property
def asset(self):
return asset
class ExampleNonStackable(NonStackableItem):
@property
def characteristic(self):
return characteristic
@property
def asset(self):
return asset
class TestStackableItems(unittest.TestCase):
def setUp(self):
self.item = ExampleStackable()
def test_item_defaults(self):
self.assertEqual(self.item.count, 1)
self.assertEqual(self.item.characteristic, characteristic)
self.assertEqual(self.item.asset, asset)
def test_add_item(self):
self.item + 1
self.assertEqual(self.item.count, 2, msg="Add one item")
self.item + 10
self.assertEqual(self.item.count, 12, msg="Add multiple items")
def test_subtract_item(self):
self.item.count = 4
self.item - 1
self.assertEqual(self.item.count, 3, msg="Subtract 1 item")
self.item - 2
self.assertEqual(self.item.count, 1, msg="Subtract multiple items")
def test_negative_subtract(self):
with self.assertRaises(ValueError):
self.item - 1
self.assertEqual(self.item.count, 1)
def test_assign_count(self):
self.item.count = 100
self.assertEqual(self.item.count, 100)
self.item.count = 1
def test_negative_assign(self):
with self.assertRaises(ValueError):
self.item.count = 0
with self.assertRaises(ValueError):
self.item.count = -100
self.assertEqual(self.item.count, 1)
class TestNonStackableItem(unittest.TestCase):
def setUp(self):
self.item = ExampleNonStackable()
def test_item_defaults(self):
self.assertEqual(self.item.count, 1)
self.assertEqual(self.item.characteristic, characteristic)
self.assertEqual(self.item.asset, asset)
def test_add_item(self):
with self.assertRaises(ValueError):
self.item + 1
def test_subtract_item(self):
with self.assertRaises(ValueError):
self.item - 1
if __name__ == '__main__':
item_suite = unittest.TestSuite()
item_suite.addTest(TestNonStackableItem())
item_suite.addTest(TestStackableItems())
runner = unittest.TextTestRunner()
runner.run(item_suite) | 0.807992 | 0.496948 |
import numpy as np
class Player:
"""docstring for Player"""
def __init__(self, symbol):
self.symbol = symbol
class Board:
"""docstring for Board"""
def __init__(self,size):
self.num_rows = size
self.num_cols = size
self.board = [ [' ' for _ in range(self.num_rows)] for _ in range(self.num_cols)]
def draw(self):
for row_idx, row in enumerate(self.board):
for col_idx,col in enumerate(row):
if col_idx < self.num_cols-1:
print(f" {col} |",end='')
else:
print(f" {col} ",end='')
print("")
if row_idx < self.num_rows-1:
print("-" * (self.num_cols * 4))
def check_row_win(self):
for row in self.board:
if row[0] != ' ' and row.count(row[0]) == len(row):
return True
return False
def check_col_win(self):
for col_ind in range(self.num_cols):
count = 0
for row in self.board:
#print(f"col ind {col_ind} and {row[col_ind]} and {self.board}")
if row[col_ind] != ' ' and row[0] == row[col_ind]:
count += 1
#print(f"Count_Value: {count} and {self.num_cols}")
if count == self.num_cols:
return True
return False
def check_diagonal(self):
count_dia1 = 0
count_dia2 = 0
for row_idx in range(self.num_rows):
if self.board[row_idx][row_idx] != ' ' and self.board[0][0] == self.board[row_idx][row_idx]:
count_dia1 += 1
print(f"Count {count_dia1} and colum : {self.num_cols}")
if count_dia1 == self.num_rows:
return True
for col_idx in range(self.num_cols-1, -1, -1):
if self.board[abs(col_idx-2)][col_idx] != ' ' and self.board[0][2] == self.board[abs(col_idx-2)][col_idx]:
count_dia2 += 1
print(f"Count {count_dia2} and colum : {self.num_cols}")
if count_dia2 == self.num_rows:
return True
return False
class GameState:
# Class of the Game State
def __init__(self, size):
self.player_1 = Player('X')
self.player_2 = Player('O')
self.board = Board(size)
self.turn = True # When turn is true its Player_1's turn and visversa
def check(self):
# Check all Rows
if self.board.check_row_win():
return True
# Check all Columns
if self.board.check_col_win():
return True
# Check all Diagonals
if self.board.check_diagonal():
return True
return False
def check_draw(self):
for row in self.board.board:
for val in row:
if val == ' ':
return False
return True
def run(self):
self.board.draw()
while True:
if self.turn:
print("Turn : Player 1")
else:
print("Turn : Player 2")
row, col = input("Enter Row and Column :").split(' ')
row = int(row)
col = int(col)
if self.board.board[row][col] == ' ':
if self.turn:
self.board.board[row][col] = self.player_1.symbol
else:
self.board.board[row][col] = self.player_2.symbol
self.board.draw()
if self.check():
if self.turn:
print("Player 1 WON")
else:
print("Player 2 WON")
return
else:
if self.check_draw():
print("Its a Draw!!!")
return
self.turn = not self.turn
else:
print("Position Not Empty!!")
print("Welcome To Tic Tac Toe")
game = GameState(3)
game.run() | tictactoe.py | import numpy as np
class Player:
"""docstring for Player"""
def __init__(self, symbol):
self.symbol = symbol
class Board:
"""docstring for Board"""
def __init__(self,size):
self.num_rows = size
self.num_cols = size
self.board = [ [' ' for _ in range(self.num_rows)] for _ in range(self.num_cols)]
def draw(self):
for row_idx, row in enumerate(self.board):
for col_idx,col in enumerate(row):
if col_idx < self.num_cols-1:
print(f" {col} |",end='')
else:
print(f" {col} ",end='')
print("")
if row_idx < self.num_rows-1:
print("-" * (self.num_cols * 4))
def check_row_win(self):
for row in self.board:
if row[0] != ' ' and row.count(row[0]) == len(row):
return True
return False
def check_col_win(self):
for col_ind in range(self.num_cols):
count = 0
for row in self.board:
#print(f"col ind {col_ind} and {row[col_ind]} and {self.board}")
if row[col_ind] != ' ' and row[0] == row[col_ind]:
count += 1
#print(f"Count_Value: {count} and {self.num_cols}")
if count == self.num_cols:
return True
return False
def check_diagonal(self):
count_dia1 = 0
count_dia2 = 0
for row_idx in range(self.num_rows):
if self.board[row_idx][row_idx] != ' ' and self.board[0][0] == self.board[row_idx][row_idx]:
count_dia1 += 1
print(f"Count {count_dia1} and colum : {self.num_cols}")
if count_dia1 == self.num_rows:
return True
for col_idx in range(self.num_cols-1, -1, -1):
if self.board[abs(col_idx-2)][col_idx] != ' ' and self.board[0][2] == self.board[abs(col_idx-2)][col_idx]:
count_dia2 += 1
print(f"Count {count_dia2} and colum : {self.num_cols}")
if count_dia2 == self.num_rows:
return True
return False
class GameState:
# Class of the Game State
def __init__(self, size):
self.player_1 = Player('X')
self.player_2 = Player('O')
self.board = Board(size)
self.turn = True # When turn is true its Player_1's turn and visversa
def check(self):
# Check all Rows
if self.board.check_row_win():
return True
# Check all Columns
if self.board.check_col_win():
return True
# Check all Diagonals
if self.board.check_diagonal():
return True
return False
def check_draw(self):
for row in self.board.board:
for val in row:
if val == ' ':
return False
return True
def run(self):
self.board.draw()
while True:
if self.turn:
print("Turn : Player 1")
else:
print("Turn : Player 2")
row, col = input("Enter Row and Column :").split(' ')
row = int(row)
col = int(col)
if self.board.board[row][col] == ' ':
if self.turn:
self.board.board[row][col] = self.player_1.symbol
else:
self.board.board[row][col] = self.player_2.symbol
self.board.draw()
if self.check():
if self.turn:
print("Player 1 WON")
else:
print("Player 2 WON")
return
else:
if self.check_draw():
print("Its a Draw!!!")
return
self.turn = not self.turn
else:
print("Position Not Empty!!")
print("Welcome To Tic Tac Toe")
game = GameState(3)
game.run() | 0.204978 | 0.324824 |
import os
CI_MODE = bool(os.environ.get('TRAVIS', False))
if not CI_MODE:
import matplotlib
from matplotlib import patches
import matplotlib.pyplot as plt
import random
from typing import List
import networkx as nx
from airflow import DAG
from networkx.drawing.nx_agraph import graphviz_layout
from ditto.api import Transformer
from ditto.utils import TransformerUtils
def ut_relabeler(dg: nx.DiGraph):
labels = {}
for node in dg.nodes:
labels[node] = node.task_id
return labels
def ut_colorer (dg: nx.DiGraph):
color_map = []
for node in dg.nodes:
if node.task_id.startswith("tp"):
color_map.append('red')
elif node.task_id.startswith("t2p"):
color_map.append('green')
else:
color_map.append('blue')
return color_map
def debug_relabeler(dg: nx.DiGraph):
labels = {}
i = 1
for node in dg.nodes:
labels[node] = f"{i}"
i+=1
return labels
def debug_colorer (dg: nx.DiGraph):
color_map = []
for node in dg.nodes:
if Transformer.TRANSFORMED_BY_HEADER in node.params:
color_map.append('red')
else:
color_map.append('blue')
return color_map
def debug_legender (dg: nx.DiGraph):
handles = []
i = 1
for node in dg.nodes:
label = f"{i}:{node.task_id}<{node.__class__.__name__}>"
if Transformer.TRANSFORMED_BY_HEADER in node.params:
handles.append(patches.Patch(color='red', label=label))
else:
handles.append(patches.Patch(color='blue', label=label))
i += 1
return handles
def draw_dag_graphiviz_rendering(dag: DAG,
colorer=ut_colorer,
relabeler=ut_relabeler,
legender=None,
figsize=[6.4, 4.8],
legend_own_figure=False):
dg = TransformerUtils.get_digraph_from_airflow_dag(dag)
labels = {}
if relabeler:
labels = relabeler(dg)
color_map = []
if colorer:
color_map = colorer(dg)
dg.graph.setdefault('graph', {})['rankdir'] = 'LR'
dg.graph.setdefault('graph', {})['newrank'] = 'true'
plt.figure(figsize=figsize)
plt.title(dag.dag_id)
pos = graphviz_layout(dg, prog='dot', args='-Gnodesep=0.1')
rads = random.uniform(0.05, 0.1)
nx.draw_networkx(dg, pos=pos, labels=labels, font_size=8, node_color=color_map, node_size=900,
font_color='white', font_weight='bold', connectionstyle=f"arc3, rad={rads}")
if legender:
if legend_own_figure:
plt.figure()
plt.title(dag.dag_id)
plt.rcParams["legend.fontsize"] = 8
plt.legend(handles=legender(dg), ncol=2)
else:
plt.rcParams["legend.fontsize"] = 7
plt.legend(handles=legender(dg), borderaxespad=0.9, ncol=2, loc='lower center')
def show_single_dag_graphviz(dag: DAG, **kwargs):
matplotlib.use("TkAgg")
draw_dag_graphiviz_rendering(dag, **{k: v for k, v in kwargs.items() if v is not None})
plt.show()
def show_multi_dag_graphviz(daglist: List[DAG], **kwargs):
matplotlib.use("TkAgg")
i = 1
for dag in daglist:
draw_dag_graphiviz_rendering(dag, **{k: v for k, v in kwargs.items() if v is not None})
i += 1
plt.show()
def debug_dags(daglist: List[DAG], **kwargs):
show_multi_dag_graphviz(daglist,
relabeler=debug_relabeler,
colorer=debug_colorer,
legender=debug_legender,
**{k: v for k, v in kwargs.items() if v is not None}) | ditto/rendering.py | import os
CI_MODE = bool(os.environ.get('TRAVIS', False))
if not CI_MODE:
import matplotlib
from matplotlib import patches
import matplotlib.pyplot as plt
import random
from typing import List
import networkx as nx
from airflow import DAG
from networkx.drawing.nx_agraph import graphviz_layout
from ditto.api import Transformer
from ditto.utils import TransformerUtils
def ut_relabeler(dg: nx.DiGraph):
labels = {}
for node in dg.nodes:
labels[node] = node.task_id
return labels
def ut_colorer (dg: nx.DiGraph):
color_map = []
for node in dg.nodes:
if node.task_id.startswith("tp"):
color_map.append('red')
elif node.task_id.startswith("t2p"):
color_map.append('green')
else:
color_map.append('blue')
return color_map
def debug_relabeler(dg: nx.DiGraph):
labels = {}
i = 1
for node in dg.nodes:
labels[node] = f"{i}"
i+=1
return labels
def debug_colorer (dg: nx.DiGraph):
color_map = []
for node in dg.nodes:
if Transformer.TRANSFORMED_BY_HEADER in node.params:
color_map.append('red')
else:
color_map.append('blue')
return color_map
def debug_legender (dg: nx.DiGraph):
handles = []
i = 1
for node in dg.nodes:
label = f"{i}:{node.task_id}<{node.__class__.__name__}>"
if Transformer.TRANSFORMED_BY_HEADER in node.params:
handles.append(patches.Patch(color='red', label=label))
else:
handles.append(patches.Patch(color='blue', label=label))
i += 1
return handles
def draw_dag_graphiviz_rendering(dag: DAG,
colorer=ut_colorer,
relabeler=ut_relabeler,
legender=None,
figsize=[6.4, 4.8],
legend_own_figure=False):
dg = TransformerUtils.get_digraph_from_airflow_dag(dag)
labels = {}
if relabeler:
labels = relabeler(dg)
color_map = []
if colorer:
color_map = colorer(dg)
dg.graph.setdefault('graph', {})['rankdir'] = 'LR'
dg.graph.setdefault('graph', {})['newrank'] = 'true'
plt.figure(figsize=figsize)
plt.title(dag.dag_id)
pos = graphviz_layout(dg, prog='dot', args='-Gnodesep=0.1')
rads = random.uniform(0.05, 0.1)
nx.draw_networkx(dg, pos=pos, labels=labels, font_size=8, node_color=color_map, node_size=900,
font_color='white', font_weight='bold', connectionstyle=f"arc3, rad={rads}")
if legender:
if legend_own_figure:
plt.figure()
plt.title(dag.dag_id)
plt.rcParams["legend.fontsize"] = 8
plt.legend(handles=legender(dg), ncol=2)
else:
plt.rcParams["legend.fontsize"] = 7
plt.legend(handles=legender(dg), borderaxespad=0.9, ncol=2, loc='lower center')
def show_single_dag_graphviz(dag: DAG, **kwargs):
matplotlib.use("TkAgg")
draw_dag_graphiviz_rendering(dag, **{k: v for k, v in kwargs.items() if v is not None})
plt.show()
def show_multi_dag_graphviz(daglist: List[DAG], **kwargs):
matplotlib.use("TkAgg")
i = 1
for dag in daglist:
draw_dag_graphiviz_rendering(dag, **{k: v for k, v in kwargs.items() if v is not None})
i += 1
plt.show()
def debug_dags(daglist: List[DAG], **kwargs):
show_multi_dag_graphviz(daglist,
relabeler=debug_relabeler,
colorer=debug_colorer,
legender=debug_legender,
**{k: v for k, v in kwargs.items() if v is not None}) | 0.377082 | 0.321487 |
import csv
import os
import xmltodict
fileList = os.listdir("D:\\Work\\rothamsted-ecoinformatics\\yieldbooks\\")
fileList.sort()
with open("D:\\Work\\rothamsted-ecoinformatics\\yieldbooks\\2000.csv", "w", newline="") as csvfile:
fieldnames = ["year","experiment_id","title","objective","sponsors","year","plot dimensions","design","treatments","basal applications","cultivations"]
csvwriter = csv.DictWriter(csvfile, delimiter=",",quotechar="\"", quoting=csv.QUOTE_MINIMAL, fieldnames=fieldnames)
csvwriter.writeheader()
for fname in fileList:
print("fname: " + fname)
if fname.endswith(".xml"):
with open("D:\\Work\\rothamsted-ecoinformatics\\yieldbooks\\" + fname) as fd:
doc = xmltodict.parse(fd.read())
year = fname.split(".")
for rep in doc["experiments"]["experiment"]:
lines = rep.split("\n")
print(lines[0])
record = {}
counter = 0
title = ""
objective = ""
sponsors = ""
s_object = rep.find("Object:")
s_sponsor = rep.find("Sponsor:")
s_design = rep.find("Design:")
s_treatments = rep.find("Treatments:")
s_basal = rep.find("Basal applications")
s_prev_years = rep.find("For previous years")
s_whole_plot = rep.find("Whole plot dimensions")
if s_whole_plot = rep.find("Plot dimensions")
s_start = rep[0:s_object]
sp_start = s_start.split("\n")
record["year"] = year[0]
record["experiment_id"] = sp_start[0].strip()
record["title"] = " ".join(sp_start[1:]).strip()
if s_sponsor > 0:
record["objective"] = rep[s_object+8:s_sponsor].replace("\n"," ").strip()
elif s_prev_years > 0:
record["objective"] = rep[s_object+8:s_prev_years].replace("\n"," ").strip()
elif s_design > 0:
record["objective"] = rep[s_object+8:design].replace("\n"," ").strip()
if s_sponsor > 0:
record["sponsors"] = rep[s_sponsor+9:s_design].replace("\n"," ").strip()
#split on The
if s_design > 0:
record["design"] = rep[s_design+7:s_whole_plot].replace("\n"," ").strip()
if s_whole_plot > 0:
record["plot dimensions"] = rep[s_whole_plot+7:s_treatments].replace("\n"," ").strip()
csvwriter.writerow(record) | processYieldbook.py | import csv
import os
import xmltodict
fileList = os.listdir("D:\\Work\\rothamsted-ecoinformatics\\yieldbooks\\")
fileList.sort()
with open("D:\\Work\\rothamsted-ecoinformatics\\yieldbooks\\2000.csv", "w", newline="") as csvfile:
fieldnames = ["year","experiment_id","title","objective","sponsors","year","plot dimensions","design","treatments","basal applications","cultivations"]
csvwriter = csv.DictWriter(csvfile, delimiter=",",quotechar="\"", quoting=csv.QUOTE_MINIMAL, fieldnames=fieldnames)
csvwriter.writeheader()
for fname in fileList:
print("fname: " + fname)
if fname.endswith(".xml"):
with open("D:\\Work\\rothamsted-ecoinformatics\\yieldbooks\\" + fname) as fd:
doc = xmltodict.parse(fd.read())
year = fname.split(".")
for rep in doc["experiments"]["experiment"]:
lines = rep.split("\n")
print(lines[0])
record = {}
counter = 0
title = ""
objective = ""
sponsors = ""
s_object = rep.find("Object:")
s_sponsor = rep.find("Sponsor:")
s_design = rep.find("Design:")
s_treatments = rep.find("Treatments:")
s_basal = rep.find("Basal applications")
s_prev_years = rep.find("For previous years")
s_whole_plot = rep.find("Whole plot dimensions")
if s_whole_plot = rep.find("Plot dimensions")
s_start = rep[0:s_object]
sp_start = s_start.split("\n")
record["year"] = year[0]
record["experiment_id"] = sp_start[0].strip()
record["title"] = " ".join(sp_start[1:]).strip()
if s_sponsor > 0:
record["objective"] = rep[s_object+8:s_sponsor].replace("\n"," ").strip()
elif s_prev_years > 0:
record["objective"] = rep[s_object+8:s_prev_years].replace("\n"," ").strip()
elif s_design > 0:
record["objective"] = rep[s_object+8:design].replace("\n"," ").strip()
if s_sponsor > 0:
record["sponsors"] = rep[s_sponsor+9:s_design].replace("\n"," ").strip()
#split on The
if s_design > 0:
record["design"] = rep[s_design+7:s_whole_plot].replace("\n"," ").strip()
if s_whole_plot > 0:
record["plot dimensions"] = rep[s_whole_plot+7:s_treatments].replace("\n"," ").strip()
csvwriter.writerow(record) | 0.150934 | 0.056236 |
from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse
class AccountsTests(TestCase):
"""Tests for the accounts app"""
def setUp(self):
"""Creates a User for testing"""
self.test_user = User.objects.create_user(
email='<EMAIL>',
username='test_user',
password='<PASSWORD>'
)
def test_create_account_get(self):
"""Ensures that create_account shows the correct information"""
# Check if the correct template was used
with self.assertTemplateUsed('accounts/create_account.html'):
# Create a response object from information given by the server
resp = self.client.get(reverse('accounts:create_account'))
# Check various page information
self.assertContains(resp, 'Create your account!')
self.assertContains(resp, 'or Login')
self.assertContains(resp, 'Create')
def test_create_account_post(self):
"""Checks that a user can be created"""
# Create data to POST to the server
post_data = {
'username': 'new_user',
'password1': '<PASSWORD>',
'password2': '<PASSWORD>',
}
resp = self.client.post(
reverse(
'accounts:create_account',
), data=post_data
)
# Ensure that we have 2 users, one from setUp and one from the POST
self.assertEqual(len(User.objects.all()), 2)
# We should have been redirected to the account login
self.assertRedirects(resp, reverse('accounts:login'))
def test_create_account_post_invalid(self):
"""Checks if an invalid user was created"""
# Create data to POST to the server
post_data = {
'username': 'new_user',
'password1': '<PASSWORD>',
'password2': '<PASSWORD>',
}
# The user should not have been redirect and should be using the
# same GET template
with self.assertTemplateUsed('accounts/create_account.html'):
self.client.post(
reverse('accounts:create_account'),
data=post_data
)
# Ensure that we have not created a user
self.assertEqual(len(User.objects.all()), 1)
def test_login_get(self):
"""Ensures that login_user shows the correct information"""
with self.assertTemplateUsed('accounts/login.html'):
resp = self.client.get(reverse('accounts:login'))
# Check various page information
self.assertContains(resp, 'Login')
self.assertContains(resp, 'or create an account')
self.assertContains(resp, 'Username')
def test_login_post(self):
"""Ensures that a user can be logged in"""
# Create data to POST to the server
post_data = {
'username': 'test_user',
'password': '<PASSWORD>',
}
resp = self.client.post(
reverse('accounts:login'),
data=post_data
)
# We should have been redirected to the site's homepage
self.assertRedirects(resp, reverse('workshop:homepage'))
def test_login_user_invalid(self):
"""Ensures that a user can be logged in"""
# Create data to POST to the server
post_data = {
'username': 'test_user',
'password': '<PASSWORD>',
}
resp = self.client.post(
reverse('accounts:login'),
data=post_data
)
# Ensures that the user sees the proper error
self.assertContains(
resp, 'Please enter a correct username and password.'
)
def test_logout(self):
"""Ensures that a user can log out"""
# Log in the test user
self.client.login(username='test_user', password='<PASSWORD>')
resp = self.client.get(reverse('accounts:logout'))
# Check that we can not find a logged in user
with self.assertRaises(TypeError):
# If the user context is not found it will raise a TypeError
resp.context['user']
# We should have been redirected to the site's homepage
self.assertRedirects(resp, reverse('workshop:homepage')) | pizzeria/accounts/tests.py | from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse
class AccountsTests(TestCase):
"""Tests for the accounts app"""
def setUp(self):
"""Creates a User for testing"""
self.test_user = User.objects.create_user(
email='<EMAIL>',
username='test_user',
password='<PASSWORD>'
)
def test_create_account_get(self):
"""Ensures that create_account shows the correct information"""
# Check if the correct template was used
with self.assertTemplateUsed('accounts/create_account.html'):
# Create a response object from information given by the server
resp = self.client.get(reverse('accounts:create_account'))
# Check various page information
self.assertContains(resp, 'Create your account!')
self.assertContains(resp, 'or Login')
self.assertContains(resp, 'Create')
def test_create_account_post(self):
"""Checks that a user can be created"""
# Create data to POST to the server
post_data = {
'username': 'new_user',
'password1': '<PASSWORD>',
'password2': '<PASSWORD>',
}
resp = self.client.post(
reverse(
'accounts:create_account',
), data=post_data
)
# Ensure that we have 2 users, one from setUp and one from the POST
self.assertEqual(len(User.objects.all()), 2)
# We should have been redirected to the account login
self.assertRedirects(resp, reverse('accounts:login'))
def test_create_account_post_invalid(self):
"""Checks if an invalid user was created"""
# Create data to POST to the server
post_data = {
'username': 'new_user',
'password1': '<PASSWORD>',
'password2': '<PASSWORD>',
}
# The user should not have been redirect and should be using the
# same GET template
with self.assertTemplateUsed('accounts/create_account.html'):
self.client.post(
reverse('accounts:create_account'),
data=post_data
)
# Ensure that we have not created a user
self.assertEqual(len(User.objects.all()), 1)
def test_login_get(self):
"""Ensures that login_user shows the correct information"""
with self.assertTemplateUsed('accounts/login.html'):
resp = self.client.get(reverse('accounts:login'))
# Check various page information
self.assertContains(resp, 'Login')
self.assertContains(resp, 'or create an account')
self.assertContains(resp, 'Username')
def test_login_post(self):
"""Ensures that a user can be logged in"""
# Create data to POST to the server
post_data = {
'username': 'test_user',
'password': '<PASSWORD>',
}
resp = self.client.post(
reverse('accounts:login'),
data=post_data
)
# We should have been redirected to the site's homepage
self.assertRedirects(resp, reverse('workshop:homepage'))
def test_login_user_invalid(self):
"""Ensures that a user can be logged in"""
# Create data to POST to the server
post_data = {
'username': 'test_user',
'password': '<PASSWORD>',
}
resp = self.client.post(
reverse('accounts:login'),
data=post_data
)
# Ensures that the user sees the proper error
self.assertContains(
resp, 'Please enter a correct username and password.'
)
def test_logout(self):
"""Ensures that a user can log out"""
# Log in the test user
self.client.login(username='test_user', password='<PASSWORD>')
resp = self.client.get(reverse('accounts:logout'))
# Check that we can not find a logged in user
with self.assertRaises(TypeError):
# If the user context is not found it will raise a TypeError
resp.context['user']
# We should have been redirected to the site's homepage
self.assertRedirects(resp, reverse('workshop:homepage')) | 0.639173 | 0.573081 |
from scipy.stats import normaltest, ttest_ind, ks_2samp
import numpy as np
import matplotlib.pyplot as plt
class comparator():
def __init__(self,A,B,confidence=0.05,normaltest=True):
self.A = A
self.B = B
self.confidence = confidence
self.normaltest = normaltest
self.get_stat()
self.log()
def get_stat(self):
self.muA = np.mean(self.A)
self.muB = np.mean(self.B)
self.stdA = np.std(self.A)
self.stdB = np.std(self.B)
self.sterrA = float(self.stdA/np.sqrt(len(self.A)))
self.sterrB = float(self.stdB/np.sqrt(len(self.B)))
def log(self,n=20):
self.n = n
self.string = ' Log '
print('='*self.n + self.string + '='*self.n)
print('A = {}'.format(self.muA))
print('std A = {}'.format(self.stdA))
print('sterr A = {}'.format(self.sterrA))
print('B = {}'.format(self.muB))
print('std B = {}'.format(self.stdB))
print('sterr B = {}'.format(self.sterrB))
print('='*self.n + '='*len(self.string) + '='*self.n)
def plot(self,bins=50,savename=None):
plt.hist(self.A,alpha=0.5,density=True)
plt.hist(self.B,alpha=0.5,density=True)
plt.legend(['A','B'],loc='best')
plt.axvline(self.muA, color='blue', linestyle='dashed', linewidth=1)
plt.axvline(self.muB, color='orange', linestyle='dashed', linewidth=1)
if savename!=None:
plt.savefig(fname=savename)
else:
plt.show()
def compare(self):
passed = True
if self.normaltest:
_, pA = normaltest(self.A)
_, pB = normaltest(self.B)
if pA > self.confidence:
print('A - normal test: PASSED')
else :
print('A - normal test: NOT PASSED')
passed = False
if pB > self.confidence:
print('B - normal test: PASSED')
else :
print('B - normal test: NOT PASSED')
passed = False
if passed:
_, p_test0 = ttest_ind(self.A, self.B, equal_var=True)
if p_test0 < self.confidence:
print("Student's t-test: PASSED p-value={}".format(p_test0))
diff_S = True
else :
print("Student's t-test: NOT PASSED p-value={}".format(p_test0))
diff_S = False
_, p_test1 = ttest_ind(self.A, self.B, equal_var=False)
if p_test1 < self.confidence:
print("Welch's t-test: PASSED p-value={}".format(p_test1))
diff_W = True
else :
print("Welch's t-test: NOT PASSED p-value={}".format(p_test1))
diff_W = False
_, p_test2 = ks_2samp(self.A, self.B)
if p_test2 < self.confidence:
diff_KS = True
print("Kolmogorov-Smirnov test: PASSED p-value={}".format(p_test2))
else :
print("Kolmogorov-Smirnov test: NOT PASSED p-value={}".format(p_test2))
diff_KS = False
print('='*self.n + '='*len(self.string) + '='*self.n)
if np.sum([diff_S,diff_W,diff_KS])>=2 :
print('A and B are significantly different with {}% confidence'.format((1-self.confidence)*100))
return True
else :
print('A and B are NOT significantly different with {}% confidence'.format((1-self.confidence)*100))
return False
else :
print('Error: distributions are not normal - more measurements are required')
return False
if __name__=="__main__":
a = [30.02,29.99,30.11,29.97,30.01,29.99]
b = [29.89,29.93,29.72,29.98,30.02,29.98]
aa = comparator(A=a,B=b,normaltest=False)
bb = aa.compare()
aa.plot(bins=100)
print(bb) | stat_analysis/comparator.py | from scipy.stats import normaltest, ttest_ind, ks_2samp
import numpy as np
import matplotlib.pyplot as plt
class comparator():
def __init__(self,A,B,confidence=0.05,normaltest=True):
self.A = A
self.B = B
self.confidence = confidence
self.normaltest = normaltest
self.get_stat()
self.log()
def get_stat(self):
self.muA = np.mean(self.A)
self.muB = np.mean(self.B)
self.stdA = np.std(self.A)
self.stdB = np.std(self.B)
self.sterrA = float(self.stdA/np.sqrt(len(self.A)))
self.sterrB = float(self.stdB/np.sqrt(len(self.B)))
def log(self,n=20):
self.n = n
self.string = ' Log '
print('='*self.n + self.string + '='*self.n)
print('A = {}'.format(self.muA))
print('std A = {}'.format(self.stdA))
print('sterr A = {}'.format(self.sterrA))
print('B = {}'.format(self.muB))
print('std B = {}'.format(self.stdB))
print('sterr B = {}'.format(self.sterrB))
print('='*self.n + '='*len(self.string) + '='*self.n)
def plot(self,bins=50,savename=None):
plt.hist(self.A,alpha=0.5,density=True)
plt.hist(self.B,alpha=0.5,density=True)
plt.legend(['A','B'],loc='best')
plt.axvline(self.muA, color='blue', linestyle='dashed', linewidth=1)
plt.axvline(self.muB, color='orange', linestyle='dashed', linewidth=1)
if savename!=None:
plt.savefig(fname=savename)
else:
plt.show()
def compare(self):
passed = True
if self.normaltest:
_, pA = normaltest(self.A)
_, pB = normaltest(self.B)
if pA > self.confidence:
print('A - normal test: PASSED')
else :
print('A - normal test: NOT PASSED')
passed = False
if pB > self.confidence:
print('B - normal test: PASSED')
else :
print('B - normal test: NOT PASSED')
passed = False
if passed:
_, p_test0 = ttest_ind(self.A, self.B, equal_var=True)
if p_test0 < self.confidence:
print("Student's t-test: PASSED p-value={}".format(p_test0))
diff_S = True
else :
print("Student's t-test: NOT PASSED p-value={}".format(p_test0))
diff_S = False
_, p_test1 = ttest_ind(self.A, self.B, equal_var=False)
if p_test1 < self.confidence:
print("Welch's t-test: PASSED p-value={}".format(p_test1))
diff_W = True
else :
print("Welch's t-test: NOT PASSED p-value={}".format(p_test1))
diff_W = False
_, p_test2 = ks_2samp(self.A, self.B)
if p_test2 < self.confidence:
diff_KS = True
print("Kolmogorov-Smirnov test: PASSED p-value={}".format(p_test2))
else :
print("Kolmogorov-Smirnov test: NOT PASSED p-value={}".format(p_test2))
diff_KS = False
print('='*self.n + '='*len(self.string) + '='*self.n)
if np.sum([diff_S,diff_W,diff_KS])>=2 :
print('A and B are significantly different with {}% confidence'.format((1-self.confidence)*100))
return True
else :
print('A and B are NOT significantly different with {}% confidence'.format((1-self.confidence)*100))
return False
else :
print('Error: distributions are not normal - more measurements are required')
return False
if __name__=="__main__":
a = [30.02,29.99,30.11,29.97,30.01,29.99]
b = [29.89,29.93,29.72,29.98,30.02,29.98]
aa = comparator(A=a,B=b,normaltest=False)
bb = aa.compare()
aa.plot(bins=100)
print(bb) | 0.399929 | 0.475971 |
import json
import click
import networkx as nx
from networkx.readwrite import json_graph
N = 60
SPLIT = 4
@click.command()
@click.option('--horizontal_file', required=True, default='horizontal.json')
@click.option('--vertical_file', required=True, default='vertical.json')
def grids(horizontal_file, vertical_file):
"""Generates two 10x10 grids with vertically striped districts.
One grid (the A/B grid) has a 40%/60% binary partisan split along
a horizontal line, perpendicular to the districts. Another grid
(the A'/B' grid) has a 40%/60% binary partisan split along a vertical
line, parallel to the districts.
:param horizontal_file: The JSON file to dump the grid with horizontal
partisan split to.
:param vertical_file: The JSON file to dump the grid with horizontal
partisan split to.
"""
graph = nx.grid_graph(dim=[N, N])
for node in graph.nodes:
graph.nodes[node]['population'] = 1
graph.nodes[node]['district'] = (node[0] // 6) + 1
graph.nodes[node]['x'] = node[0] + 1
graph.nodes[node]['y'] = node[1] + 1
horizontal_graph = graph.copy()
vertical_graph = graph.copy()
for node in graph.nodes:
a_share = int(node[1] < SPLIT)
horizontal_graph.nodes[node]['a_share'] = a_share
horizontal_graph.nodes[node]['b_share'] = 1 - a_share
for node in vertical_graph.nodes:
a_share = int(node[0] < SPLIT)
vertical_graph.nodes[node]['a_share'] = a_share
vertical_graph.nodes[node]['b_share'] = 1 - a_share
mapping = {(x, y): (x * N) + y for x, y in horizontal_graph.nodes}
horizontal_graph = nx.relabel_nodes(horizontal_graph, mapping)
vertical_graph = nx.relabel_nodes(vertical_graph, mapping)
with open(horizontal_file, 'w') as adj_file:
json.dump(json_graph.adjacency_data(horizontal_graph), adj_file)
with open(vertical_file, 'w') as adj_file:
json.dump(json_graph.adjacency_data(vertical_graph), adj_file)
if __name__ == '__main__':
grids() | tests/fixtures/grids.py | import json
import click
import networkx as nx
from networkx.readwrite import json_graph
N = 60
SPLIT = 4
@click.command()
@click.option('--horizontal_file', required=True, default='horizontal.json')
@click.option('--vertical_file', required=True, default='vertical.json')
def grids(horizontal_file, vertical_file):
"""Generates two 10x10 grids with vertically striped districts.
One grid (the A/B grid) has a 40%/60% binary partisan split along
a horizontal line, perpendicular to the districts. Another grid
(the A'/B' grid) has a 40%/60% binary partisan split along a vertical
line, parallel to the districts.
:param horizontal_file: The JSON file to dump the grid with horizontal
partisan split to.
:param vertical_file: The JSON file to dump the grid with horizontal
partisan split to.
"""
graph = nx.grid_graph(dim=[N, N])
for node in graph.nodes:
graph.nodes[node]['population'] = 1
graph.nodes[node]['district'] = (node[0] // 6) + 1
graph.nodes[node]['x'] = node[0] + 1
graph.nodes[node]['y'] = node[1] + 1
horizontal_graph = graph.copy()
vertical_graph = graph.copy()
for node in graph.nodes:
a_share = int(node[1] < SPLIT)
horizontal_graph.nodes[node]['a_share'] = a_share
horizontal_graph.nodes[node]['b_share'] = 1 - a_share
for node in vertical_graph.nodes:
a_share = int(node[0] < SPLIT)
vertical_graph.nodes[node]['a_share'] = a_share
vertical_graph.nodes[node]['b_share'] = 1 - a_share
mapping = {(x, y): (x * N) + y for x, y in horizontal_graph.nodes}
horizontal_graph = nx.relabel_nodes(horizontal_graph, mapping)
vertical_graph = nx.relabel_nodes(vertical_graph, mapping)
with open(horizontal_file, 'w') as adj_file:
json.dump(json_graph.adjacency_data(horizontal_graph), adj_file)
with open(vertical_file, 'w') as adj_file:
json.dump(json_graph.adjacency_data(vertical_graph), adj_file)
if __name__ == '__main__':
grids() | 0.572364 | 0.347343 |
import numpy as np
class Board:
def __init__(self, n=3):
self.n = n
self.N = n ** 2
self.last_move = None
self.pieces = np.zeros((self.N, self.N)).astype(int)
self.win_status = np.zeros((n, n)).astype(int)
def copy(self, other):
self.n = other.n
self.N = other.N
self.last_move = other.last_move
self.pieces = np.copy(other.pieces)
self.win_status = np.copy(other.win_status)
def __getitem__(self, index):
return self.pieces[index]
def get_legal_moves(self):
moves = set()
legal_coord = self.get_legal_area()
if legal_coord and not (self.is_locked(legal_coord[0], legal_coord[1]) or
self.is_full(legal_coord[0], legal_coord[1])):
for x in range(legal_coord[0] * self.n, (legal_coord[0] + 1) * self.n):
for y in range(legal_coord[1] * self.n, (legal_coord[1] + 1) * self.n):
if self[x][y] == 0:
legal_move = (x, y)
moves.add(legal_move)
else:
for x in range(self.N):
for y in range(self.N):
area_coord = self.get_area(x, y)
if legal_coord:
if area_coord != legal_coord and not self.is_locked(area_coord[0], area_coord[1]):
if self[x][y] == 0:
legal_move = (x, y)
moves.add(legal_move)
else:
if self[x][y] == 0:
legal_move = (x, y)
moves.add(legal_move)
return list(moves)
def get_area(self, x, y):
area_x = x // self.n
area_y = y // self.n
return area_x, area_y
def get_legal_area(self):
if not self.last_move:
return None
return self.last_move[0] % self.n, self.last_move[1] % self.n
def is_locked(self, x, y):
return self.win_status[x][y] != 0
def has_legal_moves(self):
return len(self.get_legal_moves()) != 0
def is_win(self, player):
win = self.n
# check y-strips
for y in range(self.n):
count = 0
for x in range(self.n):
if self.win_status[x][y] == player:
count += 1
if count == win:
return True
# check x-strips
for x in range(self.n):
count = 0
for y in range(self.n):
if self.win_status[x][y] == player:
count += 1
if count == win:
return True
# check two diagonal strips
count = 0
for d in range(self.n):
if self.win_status[d][d] == player:
count += 1
if count == win:
return True
count = 0
for d in range(self.n):
if self.win_status[d][self.n - d - 1] == player:
count += 1
if count == win:
return True
return False
def is_local_win(self, area, player):
win = self.n
# check y-strips
for y in range(area[1] * self.n, (area[1] + 1) * self.n):
count = 0
for x in range(area[0] * self.n, (area[0] + 1) * self.n):
if self[x][y] == player:
count += 1
if count == win:
return True
# check x-strips
for x in range(area[0] * self.n, (area[0] + 1) * self.n):
count = 0
for y in range(area[1] * self.n, (area[1] + 1) * self.n):
if self[x][y] == player:
count += 1
if count == win:
return True
# check two diagonal strips
count = 0
for x, y in \
zip(range(area[0] * self.n, (area[0] + 1) * self.n), range(area[1] * self.n, (area[1] + 1) * self.n)):
if self[x][y] == player:
count += 1
if count == win:
return True
count = 0
for x, y in \
zip(range(area[0] * self.n, (area[0] + 1) * self.n), range(area[1] * self.n, (area[1] + 1) * self.n)):
if self[x][area[1] * self.n + (area[1] + 1) * self.n - y - 1] == player:
count += 1
if count == win:
return True
return False
def execute_move(self, move, player):
(x, y) = move
assert self[x][y] == 0
self[x][y] = player
self.last_move = move
area_x, area_y = self.get_area(x, y)
if self.is_local_win((area_x, area_y), player):
self.win_status[area_x][area_y] = player
def get_canonical_form(self, player):
self.pieces = player * self.pieces
self.win_status = player * self.win_status
def rot90(self, i, copy=False):
if copy:
board = Board(self.n)
board.copy(self)
board.pieces = np.rot90(board.pieces, i)
board.win_status = np.rot90(board.win_status, i)
return board
else:
self.pieces = np.rot90(self.pieces, i)
self.win_status = np.rot90(self.win_status, i)
return True
def fliplr(self, copy=False):
if copy:
board = Board(self.n)
board.copy(self)
board.pieces = np.fliplr(board.pieces)
board.win_status = np.fliplr(board.win_status)
return board
else:
self.pieces = np.fliplr(self.pieces)
self.win_status = np.fliplr(self.win_status)
return True
def tostring(self):
return np.array(self.pieces).tostring()
def is_full(self, x0, y0):
for y in range(y0 * self.n, (y0 + 1) * self.n):
for x in range(x0 * self.n, (x0 + 1) * self.n):
if not self[x][y]:
return False
return True | ultimate_tictactoe/UltimateTicTacToeLogic.py | import numpy as np
class Board:
def __init__(self, n=3):
self.n = n
self.N = n ** 2
self.last_move = None
self.pieces = np.zeros((self.N, self.N)).astype(int)
self.win_status = np.zeros((n, n)).astype(int)
def copy(self, other):
self.n = other.n
self.N = other.N
self.last_move = other.last_move
self.pieces = np.copy(other.pieces)
self.win_status = np.copy(other.win_status)
def __getitem__(self, index):
return self.pieces[index]
def get_legal_moves(self):
moves = set()
legal_coord = self.get_legal_area()
if legal_coord and not (self.is_locked(legal_coord[0], legal_coord[1]) or
self.is_full(legal_coord[0], legal_coord[1])):
for x in range(legal_coord[0] * self.n, (legal_coord[0] + 1) * self.n):
for y in range(legal_coord[1] * self.n, (legal_coord[1] + 1) * self.n):
if self[x][y] == 0:
legal_move = (x, y)
moves.add(legal_move)
else:
for x in range(self.N):
for y in range(self.N):
area_coord = self.get_area(x, y)
if legal_coord:
if area_coord != legal_coord and not self.is_locked(area_coord[0], area_coord[1]):
if self[x][y] == 0:
legal_move = (x, y)
moves.add(legal_move)
else:
if self[x][y] == 0:
legal_move = (x, y)
moves.add(legal_move)
return list(moves)
def get_area(self, x, y):
area_x = x // self.n
area_y = y // self.n
return area_x, area_y
def get_legal_area(self):
if not self.last_move:
return None
return self.last_move[0] % self.n, self.last_move[1] % self.n
def is_locked(self, x, y):
return self.win_status[x][y] != 0
def has_legal_moves(self):
return len(self.get_legal_moves()) != 0
def is_win(self, player):
win = self.n
# check y-strips
for y in range(self.n):
count = 0
for x in range(self.n):
if self.win_status[x][y] == player:
count += 1
if count == win:
return True
# check x-strips
for x in range(self.n):
count = 0
for y in range(self.n):
if self.win_status[x][y] == player:
count += 1
if count == win:
return True
# check two diagonal strips
count = 0
for d in range(self.n):
if self.win_status[d][d] == player:
count += 1
if count == win:
return True
count = 0
for d in range(self.n):
if self.win_status[d][self.n - d - 1] == player:
count += 1
if count == win:
return True
return False
def is_local_win(self, area, player):
win = self.n
# check y-strips
for y in range(area[1] * self.n, (area[1] + 1) * self.n):
count = 0
for x in range(area[0] * self.n, (area[0] + 1) * self.n):
if self[x][y] == player:
count += 1
if count == win:
return True
# check x-strips
for x in range(area[0] * self.n, (area[0] + 1) * self.n):
count = 0
for y in range(area[1] * self.n, (area[1] + 1) * self.n):
if self[x][y] == player:
count += 1
if count == win:
return True
# check two diagonal strips
count = 0
for x, y in \
zip(range(area[0] * self.n, (area[0] + 1) * self.n), range(area[1] * self.n, (area[1] + 1) * self.n)):
if self[x][y] == player:
count += 1
if count == win:
return True
count = 0
for x, y in \
zip(range(area[0] * self.n, (area[0] + 1) * self.n), range(area[1] * self.n, (area[1] + 1) * self.n)):
if self[x][area[1] * self.n + (area[1] + 1) * self.n - y - 1] == player:
count += 1
if count == win:
return True
return False
def execute_move(self, move, player):
(x, y) = move
assert self[x][y] == 0
self[x][y] = player
self.last_move = move
area_x, area_y = self.get_area(x, y)
if self.is_local_win((area_x, area_y), player):
self.win_status[area_x][area_y] = player
def get_canonical_form(self, player):
self.pieces = player * self.pieces
self.win_status = player * self.win_status
def rot90(self, i, copy=False):
if copy:
board = Board(self.n)
board.copy(self)
board.pieces = np.rot90(board.pieces, i)
board.win_status = np.rot90(board.win_status, i)
return board
else:
self.pieces = np.rot90(self.pieces, i)
self.win_status = np.rot90(self.win_status, i)
return True
def fliplr(self, copy=False):
if copy:
board = Board(self.n)
board.copy(self)
board.pieces = np.fliplr(board.pieces)
board.win_status = np.fliplr(board.win_status)
return board
else:
self.pieces = np.fliplr(self.pieces)
self.win_status = np.fliplr(self.win_status)
return True
def tostring(self):
return np.array(self.pieces).tostring()
def is_full(self, x0, y0):
for y in range(y0 * self.n, (y0 + 1) * self.n):
for x in range(x0 * self.n, (x0 + 1) * self.n):
if not self[x][y]:
return False
return True | 0.484624 | 0.375191 |
from mlutils.simpleknn.template_selector import TemplateSelector
from mlutils.simpleknn.templates import Develop
from mlutils.version import __email__, __author__, __version__ # noqa
class SimpleKNN(object):
"""
A simplistic KNN (K Nearest Neighbors) indexing with names as keys
"""
def __new__(cls, *args, **kwargs):
strategy = kwargs.get('strategy')
return TemplateSelector.select(strategy)(*args, **kwargs)
# class NamedKNN(object):
# """
# A simplistic KNN (K Nearest Neighbors) indexing with names as keys
# """
# def __init__(self, dims, metric='angular', strategy=None):
# self.dims = dims
# self.metric = metric
# self.names = defaultdict(int)
# self._built = False
# if strategy is None:
# self.strategy = StrategySelector.select()(dims, metric)
# else:
# if isinstance(strategy, str):
# self.strategy = StrategySelector.select(strategy)(dims, metric)
# else:
# assert issubclass(strategy, BaseStrategy), 'Invalid Strategy'
# self.strategy = strategy(dims, metric)
# def __len__(self):
# return len(self.names.keys())
# @property
# def built(self):
# return self._built
# @built.setter
# def built(self, v):
# assert self._built is False, 'Index already built, cannot rebuild'
# self._built = True
# def distance(self, name1, name2):
# return self.strategy.distance(self.names[name1], self.names[name2])
# def vector(self, name):
# return self.strategy.vector(self.names[name])
# def insert(self, name, vector):
# assert name not in self.names, 'Duplicate name `{name}` encountered'
# assert self.built is False, \
# 'Index already built, can\'t insert new items'
# self.names[name] += len(self.names.keys())
# self.strategy.insert(self.names[name], vector)
# def insertMany(self, items):
# for name, vector in items:
# self.insert(name, vector)
# def build(self, **kwargs):
# '''
# builds the index
# parameters are dependent on other strategies
# and has different meaning for different strategies
# develop strategy doesn't really builds an index so
# parameters are simply ignored
# '''
# self.strategy.build(**kwargs)
# self.built = True
# def nearestByName(self, name, n=10):
# return self.nearestByVector(self.vec(name), n)
# def nearestByVector(self, vector, n=10):
# return [
# (self.names[i], vec)
# for i, vec
# in self.strategy.nearestByVector(vector, n)
# ]
# def save(self, file_name):
# '''Saving SimpleKNN data'''
# with open(f'{file_name}-data.pkl', 'wb', encoding='utf-8') as f:
# pickle.dump({
# 'dims': self.dims,
# 'metric': self.metric,
# 'built': self.built,
# 'strategy': self.strategy.__class__
# }, f)
# '''Saving strategyic data'''
# self.strategy.save(file_name)
# @classmethod
# def load(klass, file_name):
# '''Loading SimpleKNN data'''
# with open(f'{file_name}-data.pkl', 'rb', encoding='utf-8') as f:
# data = pickle.load(f)
# obj = klass(
# dims=data.dims,
# metric=data['metric'],
# strategy=data['strategy']
# )
# obj.built = obj['built']
# '''Loading strategyic data'''
# obj.strategy.load(file_name)
# return obj | mlutils/simpleknn/__init__.py | from mlutils.simpleknn.template_selector import TemplateSelector
from mlutils.simpleknn.templates import Develop
from mlutils.version import __email__, __author__, __version__ # noqa
class SimpleKNN(object):
"""
A simplistic KNN (K Nearest Neighbors) indexing with names as keys
"""
def __new__(cls, *args, **kwargs):
strategy = kwargs.get('strategy')
return TemplateSelector.select(strategy)(*args, **kwargs)
# class NamedKNN(object):
# """
# A simplistic KNN (K Nearest Neighbors) indexing with names as keys
# """
# def __init__(self, dims, metric='angular', strategy=None):
# self.dims = dims
# self.metric = metric
# self.names = defaultdict(int)
# self._built = False
# if strategy is None:
# self.strategy = StrategySelector.select()(dims, metric)
# else:
# if isinstance(strategy, str):
# self.strategy = StrategySelector.select(strategy)(dims, metric)
# else:
# assert issubclass(strategy, BaseStrategy), 'Invalid Strategy'
# self.strategy = strategy(dims, metric)
# def __len__(self):
# return len(self.names.keys())
# @property
# def built(self):
# return self._built
# @built.setter
# def built(self, v):
# assert self._built is False, 'Index already built, cannot rebuild'
# self._built = True
# def distance(self, name1, name2):
# return self.strategy.distance(self.names[name1], self.names[name2])
# def vector(self, name):
# return self.strategy.vector(self.names[name])
# def insert(self, name, vector):
# assert name not in self.names, 'Duplicate name `{name}` encountered'
# assert self.built is False, \
# 'Index already built, can\'t insert new items'
# self.names[name] += len(self.names.keys())
# self.strategy.insert(self.names[name], vector)
# def insertMany(self, items):
# for name, vector in items:
# self.insert(name, vector)
# def build(self, **kwargs):
# '''
# builds the index
# parameters are dependent on other strategies
# and has different meaning for different strategies
# develop strategy doesn't really builds an index so
# parameters are simply ignored
# '''
# self.strategy.build(**kwargs)
# self.built = True
# def nearestByName(self, name, n=10):
# return self.nearestByVector(self.vec(name), n)
# def nearestByVector(self, vector, n=10):
# return [
# (self.names[i], vec)
# for i, vec
# in self.strategy.nearestByVector(vector, n)
# ]
# def save(self, file_name):
# '''Saving SimpleKNN data'''
# with open(f'{file_name}-data.pkl', 'wb', encoding='utf-8') as f:
# pickle.dump({
# 'dims': self.dims,
# 'metric': self.metric,
# 'built': self.built,
# 'strategy': self.strategy.__class__
# }, f)
# '''Saving strategyic data'''
# self.strategy.save(file_name)
# @classmethod
# def load(klass, file_name):
# '''Loading SimpleKNN data'''
# with open(f'{file_name}-data.pkl', 'rb', encoding='utf-8') as f:
# data = pickle.load(f)
# obj = klass(
# dims=data.dims,
# metric=data['metric'],
# strategy=data['strategy']
# )
# obj.built = obj['built']
# '''Loading strategyic data'''
# obj.strategy.load(file_name)
# return obj | 0.67854 | 0.148047 |
# LIBRERÍAS
from imutils.video import FileVideoStream # Gestión de video
import numpy as np # Soporte vectores y matrices
import imutils
import cv2
import time
import os, random
from cvlib.object_detection import draw_bbox # Detección de objetos
import cvlib as cv # Detección de objetos
from inputimeout import inputimeout, TimeoutOccurred
# Funciones de estilos en fichero estilos.py
from config.estilos import convertoasci, mostrar_cargando, imprtextos, limpiarterminal
# Funciones generales en fichero funciones.py
from config.funciones import importarjson, impdiccionario, pathrevision
# ANIMACIONES DE LANZAMIENTO
# - Limpiar terminal antes de ejecutar la app
limpiarterminal()
# - Mensajes de inicio
titulo_inicio = convertoasci("Computer Vision APP v 1.7t")
print(titulo_inicio)
# Funcion imprime texto inicio
imprtextos('inicio')
# - Barra de animación de carga
mostrar_cargando()
# Espera 0.5 y limpia la pantalla después de la intro.
print("\nInicio completado.")
limpiarterminal()
# - Imprime ASCI art el título orígenes
titulo_origenes = convertoasci("ORIGENES")
print(titulo_origenes)
print('~ Las fuentes son de internet y no está garantizado que funcionen siempre. \n')
# - Funcion que imprime todos los nombres del diccionario origenes
source_origenes = 'config\\origenes.json'
# - Funcion reconocimiento del path de archivos en windows, mac o linux
tratamientopath = pathrevision(source_origenes)
origenes = importarjson(tratamientopath)
impdiccionario(origenes)
# - Input por terminal al usuario definiendo el origen (con timeout)
# - Si no se introduce input por defecto selecciona uno aleatorio.
try:
origen_def = inputimeout(
prompt='\nEscribe el NOMBRE del orígen: ', timeout=10)
while origen_def != origenes:
if origen_def in origenes:
limpiarterminal()
print('\n\nOrígen seleccionado: ', origen_def, '\n\n')
time.sleep(2)
# - Lee del diccionario de orígenes con el seleccionado
origen_in = origenes[origen_def]
time.sleep(1)
limpiarterminal()
break
else:
limpiarterminal()
print(titulo_origenes)
print('~ Las fuentes son de internet y no está garantizado que funcionen siempre. \n')
impdiccionario(origenes)
print ('\nERROR: El nombre que has introducido no existe en la lista de orígenes.')
origen_def = inputimeout(
prompt='\nEscribe el NOMBRE del orígen: ', timeout=10)
except TimeoutOccurred:
origen_def = random.choice(list(origenes.keys())) # Para obtener un valor key random del diccionario origenes
origen_in = origenes[origen_def]
print('\n\n---> AL no intriducir ningún valor se ha seleccionado automáticamente', origen_def+'.')
time.sleep(3)
limpiarterminal()
# - Imprime ASCI art el título modelo
titulo_modelo = convertoasci("MODELO DE I.A.")
print(titulo_modelo)
# Funcion imprime texto de modelo
imprtextos('modelo')
list(origenes)
# - Imprime todos los nombre del diccionario de modelos
# - Funcion que imprime todos los nombres del diccionario modelos
source_modelos = 'config\\modelos.json'
# - Funcion reconocimiento del path de archivos en windows, mac o linux
tratamientopath = pathrevision(source_modelos)
modelos = importarjson(tratamientopath)
impdiccionario(modelos)
# - Input por terminal al usuario definiendo el modelo de yolo (con timeout)
try:
modelo_def = inputimeout(
prompt='\nEscribe el NOMBRE del modelo: ', timeout=3)
if not modelo_def:
modelo_def = 'Preciso'
except TimeoutOccurred:
modelo_def = 'Preciso'
print('\n--> No se ha introducido un valor. Selección automática activada.')
time.sleep(1)
# - Lee el origen de datos definido por el input de usuario anterior
modelo_in = modelos[modelo_def]
# - Comprueba el modelo seleccionado e imprime la advertencia describiendo el modelo
print('\n·Modelo de computación seleccionado:', modelo_def)
if modelo_def == 'Rapido':
print('~ Recuerda que este modelo es más rápido pero menos preciso.')
else:
print('~ Recuerda que este modelo es más lento pero más preciso.')
# FORMATOS DE ESTILO EN PANTALLA
tipofuente = cv2.FONT_HERSHEY_SIMPLEX
tamanofuente = 0.8
grosorfuente = 1
# - Autos
colorfuente_coches = 0, 0, 255 # BRG
postexto_coches = 40, 50
colorfuente_camiones = 0, 0, 255 # BRG
postexto_camiones = 40, 80
# - Humanos
colorfuente_personas = 255, 0, 0 # BRG
postexto_personas = 40, 120
## Aún no implementada la funión.
colorfuente_hombres = 255, 0, 0 # BRG
postexto_hombres = 40, 160
## Aún no implementada la funión.
colorfuente_mujeres = 255, 0, 0 # BRG
postexto_mujeres = 40, 200
# GESTIÓN DE MEDIOS
# Iniciando fuente de video
fvs = FileVideoStream(origen_in).start()
print('\nProcesando fuente multimedia...')
time.sleep(1)
print('\nMostrando visualizador...\n')
# - Gestionando el video frame a frame
while fvs.more():
# - Leer fuente de video
videoproceso = fvs.read()
# - Reajuste de tamano
videoproceso = imutils.resize(videoproceso, width=1280)
# - Conversión de color a blanco y negro
videoproceso = cv2.cvtColor(videoproceso, cv2.COLOR_BGR2GRAY)
# - Matriz
videoproceso = np.dstack([videoproceso, videoproceso, videoproceso])
# DETECTORES DE VISIÓN POR COMPUTADORA
# - Detector de objetos
bbox, label, conf = cv.detect_common_objects(videoproceso, model=modelo_in)
# - Detector de rostros
#faces, confidences = cv.detect_face(videoproceso)
# - Detector de género
#label, confidence = cv.detect_gender(videoproceso)
# - Limpiar pantalla del terminal en cada frame
os.system('cls' if os.name == 'nt' else "printf '\033c'")
# - Mensajes de consola en captura
titulo_capturando = convertoasci("Computer Vision APP v 1.7t")
print(titulo_capturando)
# Funcion imprime texto de consola
imprtextos('consola')
print('·Modelo:', modelo_def, ' ·Fuente:', origen_def, ' \n')
print('Para cerrar la ventana de visualización pulsando la tecla "Q" o con "Control+C en el terminal."')
# Procesado del display layout
out = draw_bbox(videoproceso, bbox, label, conf)
# CONTADORES EN PANTALLA STREAM
# - Contador Personas
out = cv2.putText(videoproceso, 'Coches: '+str(label.count('car')), (postexto_coches),
tipofuente, tamanofuente, (colorfuente_coches), grosorfuente, cv2.LINE_AA)
# - Contador Camiones
out = cv2.putText(videoproceso, 'Camiones: '+str(label.count('truck')), (postexto_camiones),
tipofuente, tamanofuente, (colorfuente_camiones), grosorfuente, cv2.LINE_AA)
# - Contador Personas
out = cv2.putText(videoproceso, 'Personas: '+str(label.count('person')), (postexto_personas),
tipofuente, tamanofuente, (colorfuente_personas), grosorfuente, cv2.LINE_AA)
# Pendiente implementar - Detección de género
#out = cv2.putText(videoproceso,'Hombres: '+str(label.count('male')),(postexto_hombres),tipofuente,tamanofuente,(colorfuente_hombres),grosorfuente,cv2.LINE_AA)
#out = cv2.putText(videoproceso,'Mujeres: '+str(label.count('female')),(postexto_mujeres),tipofuente,tamanofuente,(colorfuente_mujeres),grosorfuente,cv2.LINE_AA)
cv2.imshow('(CVAPP) Computer Vision APP {origen_def} - Powered by @flowese',
out) # Título de la ventana
if cv2.waitKey(10) & 0xFF == ord('q'): # Pulsar tecla Q para salir
break
# CERRAR VENTANAS
imprtextos('final')
cv2.destroyAllWindows() | CVAPP-Computer-Vision Desktop/CVAPP.py |
# LIBRERÍAS
from imutils.video import FileVideoStream # Gestión de video
import numpy as np # Soporte vectores y matrices
import imutils
import cv2
import time
import os, random
from cvlib.object_detection import draw_bbox # Detección de objetos
import cvlib as cv # Detección de objetos
from inputimeout import inputimeout, TimeoutOccurred
# Funciones de estilos en fichero estilos.py
from config.estilos import convertoasci, mostrar_cargando, imprtextos, limpiarterminal
# Funciones generales en fichero funciones.py
from config.funciones import importarjson, impdiccionario, pathrevision
# ANIMACIONES DE LANZAMIENTO
# - Limpiar terminal antes de ejecutar la app
limpiarterminal()
# - Mensajes de inicio
titulo_inicio = convertoasci("Computer Vision APP v 1.7t")
print(titulo_inicio)
# Funcion imprime texto inicio
imprtextos('inicio')
# - Barra de animación de carga
mostrar_cargando()
# Espera 0.5 y limpia la pantalla después de la intro.
print("\nInicio completado.")
limpiarterminal()
# - Imprime ASCI art el título orígenes
titulo_origenes = convertoasci("ORIGENES")
print(titulo_origenes)
print('~ Las fuentes son de internet y no está garantizado que funcionen siempre. \n')
# - Funcion que imprime todos los nombres del diccionario origenes
source_origenes = 'config\\origenes.json'
# - Funcion reconocimiento del path de archivos en windows, mac o linux
tratamientopath = pathrevision(source_origenes)
origenes = importarjson(tratamientopath)
impdiccionario(origenes)
# - Input por terminal al usuario definiendo el origen (con timeout)
# - Si no se introduce input por defecto selecciona uno aleatorio.
try:
origen_def = inputimeout(
prompt='\nEscribe el NOMBRE del orígen: ', timeout=10)
while origen_def != origenes:
if origen_def in origenes:
limpiarterminal()
print('\n\nOrígen seleccionado: ', origen_def, '\n\n')
time.sleep(2)
# - Lee del diccionario de orígenes con el seleccionado
origen_in = origenes[origen_def]
time.sleep(1)
limpiarterminal()
break
else:
limpiarterminal()
print(titulo_origenes)
print('~ Las fuentes son de internet y no está garantizado que funcionen siempre. \n')
impdiccionario(origenes)
print ('\nERROR: El nombre que has introducido no existe en la lista de orígenes.')
origen_def = inputimeout(
prompt='\nEscribe el NOMBRE del orígen: ', timeout=10)
except TimeoutOccurred:
origen_def = random.choice(list(origenes.keys())) # Para obtener un valor key random del diccionario origenes
origen_in = origenes[origen_def]
print('\n\n---> AL no intriducir ningún valor se ha seleccionado automáticamente', origen_def+'.')
time.sleep(3)
limpiarterminal()
# - Imprime ASCI art el título modelo
titulo_modelo = convertoasci("MODELO DE I.A.")
print(titulo_modelo)
# Funcion imprime texto de modelo
imprtextos('modelo')
list(origenes)
# - Imprime todos los nombre del diccionario de modelos
# - Funcion que imprime todos los nombres del diccionario modelos
source_modelos = 'config\\modelos.json'
# - Funcion reconocimiento del path de archivos en windows, mac o linux
tratamientopath = pathrevision(source_modelos)
modelos = importarjson(tratamientopath)
impdiccionario(modelos)
# - Input por terminal al usuario definiendo el modelo de yolo (con timeout)
try:
modelo_def = inputimeout(
prompt='\nEscribe el NOMBRE del modelo: ', timeout=3)
if not modelo_def:
modelo_def = 'Preciso'
except TimeoutOccurred:
modelo_def = 'Preciso'
print('\n--> No se ha introducido un valor. Selección automática activada.')
time.sleep(1)
# - Lee el origen de datos definido por el input de usuario anterior
modelo_in = modelos[modelo_def]
# - Comprueba el modelo seleccionado e imprime la advertencia describiendo el modelo
print('\n·Modelo de computación seleccionado:', modelo_def)
if modelo_def == 'Rapido':
print('~ Recuerda que este modelo es más rápido pero menos preciso.')
else:
print('~ Recuerda que este modelo es más lento pero más preciso.')
# FORMATOS DE ESTILO EN PANTALLA
tipofuente = cv2.FONT_HERSHEY_SIMPLEX
tamanofuente = 0.8
grosorfuente = 1
# - Autos
colorfuente_coches = 0, 0, 255 # BRG
postexto_coches = 40, 50
colorfuente_camiones = 0, 0, 255 # BRG
postexto_camiones = 40, 80
# - Humanos
colorfuente_personas = 255, 0, 0 # BRG
postexto_personas = 40, 120
## Aún no implementada la funión.
colorfuente_hombres = 255, 0, 0 # BRG
postexto_hombres = 40, 160
## Aún no implementada la funión.
colorfuente_mujeres = 255, 0, 0 # BRG
postexto_mujeres = 40, 200
# GESTIÓN DE MEDIOS
# Iniciando fuente de video
fvs = FileVideoStream(origen_in).start()
print('\nProcesando fuente multimedia...')
time.sleep(1)
print('\nMostrando visualizador...\n')
# - Gestionando el video frame a frame
while fvs.more():
# - Leer fuente de video
videoproceso = fvs.read()
# - Reajuste de tamano
videoproceso = imutils.resize(videoproceso, width=1280)
# - Conversión de color a blanco y negro
videoproceso = cv2.cvtColor(videoproceso, cv2.COLOR_BGR2GRAY)
# - Matriz
videoproceso = np.dstack([videoproceso, videoproceso, videoproceso])
# DETECTORES DE VISIÓN POR COMPUTADORA
# - Detector de objetos
bbox, label, conf = cv.detect_common_objects(videoproceso, model=modelo_in)
# - Detector de rostros
#faces, confidences = cv.detect_face(videoproceso)
# - Detector de género
#label, confidence = cv.detect_gender(videoproceso)
# - Limpiar pantalla del terminal en cada frame
os.system('cls' if os.name == 'nt' else "printf '\033c'")
# - Mensajes de consola en captura
titulo_capturando = convertoasci("Computer Vision APP v 1.7t")
print(titulo_capturando)
# Funcion imprime texto de consola
imprtextos('consola')
print('·Modelo:', modelo_def, ' ·Fuente:', origen_def, ' \n')
print('Para cerrar la ventana de visualización pulsando la tecla "Q" o con "Control+C en el terminal."')
# Procesado del display layout
out = draw_bbox(videoproceso, bbox, label, conf)
# CONTADORES EN PANTALLA STREAM
# - Contador Personas
out = cv2.putText(videoproceso, 'Coches: '+str(label.count('car')), (postexto_coches),
tipofuente, tamanofuente, (colorfuente_coches), grosorfuente, cv2.LINE_AA)
# - Contador Camiones
out = cv2.putText(videoproceso, 'Camiones: '+str(label.count('truck')), (postexto_camiones),
tipofuente, tamanofuente, (colorfuente_camiones), grosorfuente, cv2.LINE_AA)
# - Contador Personas
out = cv2.putText(videoproceso, 'Personas: '+str(label.count('person')), (postexto_personas),
tipofuente, tamanofuente, (colorfuente_personas), grosorfuente, cv2.LINE_AA)
# Pendiente implementar - Detección de género
#out = cv2.putText(videoproceso,'Hombres: '+str(label.count('male')),(postexto_hombres),tipofuente,tamanofuente,(colorfuente_hombres),grosorfuente,cv2.LINE_AA)
#out = cv2.putText(videoproceso,'Mujeres: '+str(label.count('female')),(postexto_mujeres),tipofuente,tamanofuente,(colorfuente_mujeres),grosorfuente,cv2.LINE_AA)
cv2.imshow('(CVAPP) Computer Vision APP {origen_def} - Powered by @flowese',
out) # Título de la ventana
if cv2.waitKey(10) & 0xFF == ord('q'): # Pulsar tecla Q para salir
break
# CERRAR VENTANAS
imprtextos('final')
cv2.destroyAllWindows() | 0.155976 | 0.188997 |
import sqlite3
conn = sqlite3.connect('northwind_small.sqlite3')
cursor = conn.cursor()
#What are the most expensive items in the database
query1 = '''
SELECT
ProductName,
UnitPrice
FROM Product
ORDER BY
UnitPrice DESC
LIMIT 10;
'''
result = cursor.execute(query1).fetchall()
print(f'Ten Most Expensive Items {result}')
#What is the average age of employee at time of hiring
query2 = '''
SELECT
AVG(HireDate - BirthDate)
FROM Employee;
'''
result2 = cursor.execute(query2).fetchone()
print(f'What is the average age of employees at time of hire? {result2}')
#What are the 10 most expensive items in the database and their suppliers
query3='''
SELECT
p.ProductName,
p.UnitPrice,
s.CompanyName AS Supplier
FROM Product AS p
JOIN Supplier AS s
ON p.SupplierId = s.Id
ORDER BY
UnitPrice DESC
LIMIT 10;
'''
result3 = cursor.execute(query3).fetchall()
print(f'Ten Most Expensive Items and their supplier {result3}')
#What is the largest category by number of unique products
query4 = '''
SELECT
COUNT(DISTINCT Product.ProductName) AS UniqueProducts,
Category.CategoryName
FROM Product
JOIN Category
ON Product.CategoryId = Category.Id
GROUP BY Category.CategoryName
ORDER BY UniqueProducts DESC
LIMIT 1;
'''
result4 = cursor.execute(query4).fetchall()
print(f'What is the largest category by number of unique products? {result4}')
cursor.close()
conn.close()
#Results
'''$ python northwind.py
Ten Most Expensive Items [('<NAME>', 263.5), ('<NAME>', 123.79), ('<NAME>', 97), ("<NAME>", 81), ('<NAME>', 62.5), ('<NAME>', 55), ('<NAME>', 53), ('Tarte au sucre', 49.3), ('Ipoh Coffee', 46), ('R<NAME>', 45.6)]
What is the average age of employees at time of hire? (37.22222222222222,)
Ten Most Expensive Items and their supplier [('<NAME>', 263.5, 'Aux joyeux ecclésiastiques'), ('<NAME>', 123.79, 'Plutzer Lebensmittelgroßmärkte AG'), ('<NAME>', 97, 'Tokyo Traders'), ("<NAME>", 81, 'Specialty Biscuits, Ltd.'), ('<NAME>', 62.5, 'Pavlova, Ltd.'), ('<NAME>', 55, 'Gai pâturage'), ('<NAME>', 53, "G'day, Mate"), ('Tarte au sucre', 49.3, "Forêts d'érables"), ('Ipoh Coffee', 46, 'Leka Trading'), ('R<NAME>', 45.6, 'Plutzer Lebensmittelgroßmärkte AG')]
What is the largest category by number of unique products? [(13, 'Confections')]
(Sprint_Challange)
''' | Answers/northwind.py | import sqlite3
conn = sqlite3.connect('northwind_small.sqlite3')
cursor = conn.cursor()
#What are the most expensive items in the database
query1 = '''
SELECT
ProductName,
UnitPrice
FROM Product
ORDER BY
UnitPrice DESC
LIMIT 10;
'''
result = cursor.execute(query1).fetchall()
print(f'Ten Most Expensive Items {result}')
#What is the average age of employee at time of hiring
query2 = '''
SELECT
AVG(HireDate - BirthDate)
FROM Employee;
'''
result2 = cursor.execute(query2).fetchone()
print(f'What is the average age of employees at time of hire? {result2}')
#What are the 10 most expensive items in the database and their suppliers
query3='''
SELECT
p.ProductName,
p.UnitPrice,
s.CompanyName AS Supplier
FROM Product AS p
JOIN Supplier AS s
ON p.SupplierId = s.Id
ORDER BY
UnitPrice DESC
LIMIT 10;
'''
result3 = cursor.execute(query3).fetchall()
print(f'Ten Most Expensive Items and their supplier {result3}')
#What is the largest category by number of unique products
query4 = '''
SELECT
COUNT(DISTINCT Product.ProductName) AS UniqueProducts,
Category.CategoryName
FROM Product
JOIN Category
ON Product.CategoryId = Category.Id
GROUP BY Category.CategoryName
ORDER BY UniqueProducts DESC
LIMIT 1;
'''
result4 = cursor.execute(query4).fetchall()
print(f'What is the largest category by number of unique products? {result4}')
cursor.close()
conn.close()
#Results
'''$ python northwind.py
Ten Most Expensive Items [('<NAME>', 263.5), ('<NAME>', 123.79), ('<NAME>', 97), ("<NAME>", 81), ('<NAME>', 62.5), ('<NAME>', 55), ('<NAME>', 53), ('Tarte au sucre', 49.3), ('Ipoh Coffee', 46), ('R<NAME>', 45.6)]
What is the average age of employees at time of hire? (37.22222222222222,)
Ten Most Expensive Items and their supplier [('<NAME>', 263.5, 'Aux joyeux ecclésiastiques'), ('<NAME>', 123.79, 'Plutzer Lebensmittelgroßmärkte AG'), ('<NAME>', 97, 'Tokyo Traders'), ("<NAME>", 81, 'Specialty Biscuits, Ltd.'), ('<NAME>', 62.5, 'Pavlova, Ltd.'), ('<NAME>', 55, 'Gai pâturage'), ('<NAME>', 53, "G'day, Mate"), ('Tarte au sucre', 49.3, "Forêts d'érables"), ('Ipoh Coffee', 46, 'Leka Trading'), ('R<NAME>', 45.6, 'Plutzer Lebensmittelgroßmärkte AG')]
What is the largest category by number of unique products? [(13, 'Confections')]
(Sprint_Challange)
''' | 0.199347 | 0.312895 |
import click
from cg_manage_rds.cmds.utils import run_sync
from cg_manage_rds.cmds.engine import Engine
from cg_manage_rds.cmds import cf_cmds as cf
class MySql(Engine):
def prerequisites(self) -> None:
click.echo("Checking for locally installed mysql utilities")
cmd = ["which", "mysql"]
code, _, _ = run_sync(cmd)
if code != 0:
errstr = click.style(
"\nmysql application is required but not found", fg="red"
)
raise click.ClickException(errstr)
click.echo(click.style("\nmysql found!", fg="bright_green"))
cmd = ["which", "mysqldump"]
code, _, _ = run_sync(cmd)
if code != 0:
errstr = click.style(
"\nmysqldump application is required but not found", fg="red"
)
raise click.ClickException(errstr)
click.echo(click.style("\nmysqldump found!", fg="bright_green"))
def export_svc(
self, svc_name: str, creds: dict, backup_file: str,
options: str="", ignore: bool=False
) -> None:
click.echo(f"Exporting from MySql DB: {svc_name}")
opts=self.default_export_options(options,ignore)
base_opts = self._creds_to_opts(creds)
cmd = ["mysqldump"]
cmd.extend(base_opts)
cmd.extend(opts)
cmd.extend(["-r", backup_file, creds['db_name']])
# mysqldump -u user -p"<PASSWORD>" -h 127.0.0.1 -P 33306 -r backup_file -n --set-gtid-purged=OFF -f -y databasename
click.echo("Exporting with:")
click.echo(click.style("\t" + " ".join(cmd), fg="yellow"))
code, result, status = run_sync(cmd)
if code != 0:
click.echo(status)
raise click.ClickException(result)
click.echo(status)
click.echo("Export complete\n")
def import_svc(
self, svc_name: str, creds: dict, backup_file: str,
options: str= "", ignore: bool=False
) -> None:
# mysql -u"user" -p"passwd" -h"127.0.0.1" -P"33306" -D"databasename" -e"source backup_file"
click.echo(f"Importing to MySql DB: {svc_name}")
opts = self.default_import_options(options, ignore)
base_opts = self._creds_to_opts(creds)
cmd = ["mysql"]
cmd.extend(base_opts)
cmd.extend(opts)
cmd.extend([f"-D{creds['db_name']}", f"-e source {backup_file};"])
click.echo("Importing with:")
click.echo(click.style("\t" + " ".join(cmd), fg="yellow"))
code, result, status = run_sync(cmd)
if code != 0:
click.echo(status)
raise click.ClickException(result)
click.echo(status)
click.echo("Import complete\n")
def credentials(self, service_name: str, key_name: str = "key") -> dict:
cf.create_service_key(key_name, service_name)
creds = cf.get_service_key(key_name, service_name)
creds["local_port"] = int(creds.get("port")) + 30000
creds['local_host'] = '127.0.0.1'
creds['uri'] = f"mysql -u\"{creds['username']}\" -p\"{creds['password']}\" -h\"{creds['local_host']}\" -P\"{creds['local_port']}\" -D\"{creds['db_name']}\""
return creds
def default_export_options(self, options: str, ignore: bool = False) -> list:
if options is not None:
opts = options.split()
else:
opts = list()
if ignore:
return opts
# dont create
if not any(x in [ "-n", "--no-create-db"] for x in opts):
opts.append("-n")
# ignore tablespaces
if not any(x in [ "-y", "--tablespaces" ] for x in opts):
opts.append("-y")
# push through errors
if not any(x in [ "-f", "--force" ] for x in opts):
opts.append("-f")
if "--set-gtid-purged=OFF" not in opts:
opts.append("--set-gtid-purged=OFF")
if "--column-statistics=0" not in opts:
opts.append("--column-statistics=0")
return opts
def default_import_options(self, options: str, ignore: bool = False) -> list:
if options is not None:
opts = options.split()
else:
opts = list()
return opts
def _creds_to_opts(self,creds: dict) -> list:
opts = f"-u{creds['username']} "
opts+=f"-p{creds['password']} "
opts+=f"-P{creds['local_port']} "
opts+=f"-h{creds['local_host']} "
return opts.split() | cg_manage_rds/cmds/mysql.py | import click
from cg_manage_rds.cmds.utils import run_sync
from cg_manage_rds.cmds.engine import Engine
from cg_manage_rds.cmds import cf_cmds as cf
class MySql(Engine):
def prerequisites(self) -> None:
click.echo("Checking for locally installed mysql utilities")
cmd = ["which", "mysql"]
code, _, _ = run_sync(cmd)
if code != 0:
errstr = click.style(
"\nmysql application is required but not found", fg="red"
)
raise click.ClickException(errstr)
click.echo(click.style("\nmysql found!", fg="bright_green"))
cmd = ["which", "mysqldump"]
code, _, _ = run_sync(cmd)
if code != 0:
errstr = click.style(
"\nmysqldump application is required but not found", fg="red"
)
raise click.ClickException(errstr)
click.echo(click.style("\nmysqldump found!", fg="bright_green"))
def export_svc(
self, svc_name: str, creds: dict, backup_file: str,
options: str="", ignore: bool=False
) -> None:
click.echo(f"Exporting from MySql DB: {svc_name}")
opts=self.default_export_options(options,ignore)
base_opts = self._creds_to_opts(creds)
cmd = ["mysqldump"]
cmd.extend(base_opts)
cmd.extend(opts)
cmd.extend(["-r", backup_file, creds['db_name']])
# mysqldump -u user -p"<PASSWORD>" -h 127.0.0.1 -P 33306 -r backup_file -n --set-gtid-purged=OFF -f -y databasename
click.echo("Exporting with:")
click.echo(click.style("\t" + " ".join(cmd), fg="yellow"))
code, result, status = run_sync(cmd)
if code != 0:
click.echo(status)
raise click.ClickException(result)
click.echo(status)
click.echo("Export complete\n")
def import_svc(
self, svc_name: str, creds: dict, backup_file: str,
options: str= "", ignore: bool=False
) -> None:
# mysql -u"user" -p"passwd" -h"127.0.0.1" -P"33306" -D"databasename" -e"source backup_file"
click.echo(f"Importing to MySql DB: {svc_name}")
opts = self.default_import_options(options, ignore)
base_opts = self._creds_to_opts(creds)
cmd = ["mysql"]
cmd.extend(base_opts)
cmd.extend(opts)
cmd.extend([f"-D{creds['db_name']}", f"-e source {backup_file};"])
click.echo("Importing with:")
click.echo(click.style("\t" + " ".join(cmd), fg="yellow"))
code, result, status = run_sync(cmd)
if code != 0:
click.echo(status)
raise click.ClickException(result)
click.echo(status)
click.echo("Import complete\n")
def credentials(self, service_name: str, key_name: str = "key") -> dict:
cf.create_service_key(key_name, service_name)
creds = cf.get_service_key(key_name, service_name)
creds["local_port"] = int(creds.get("port")) + 30000
creds['local_host'] = '127.0.0.1'
creds['uri'] = f"mysql -u\"{creds['username']}\" -p\"{creds['password']}\" -h\"{creds['local_host']}\" -P\"{creds['local_port']}\" -D\"{creds['db_name']}\""
return creds
def default_export_options(self, options: str, ignore: bool = False) -> list:
if options is not None:
opts = options.split()
else:
opts = list()
if ignore:
return opts
# dont create
if not any(x in [ "-n", "--no-create-db"] for x in opts):
opts.append("-n")
# ignore tablespaces
if not any(x in [ "-y", "--tablespaces" ] for x in opts):
opts.append("-y")
# push through errors
if not any(x in [ "-f", "--force" ] for x in opts):
opts.append("-f")
if "--set-gtid-purged=OFF" not in opts:
opts.append("--set-gtid-purged=OFF")
if "--column-statistics=0" not in opts:
opts.append("--column-statistics=0")
return opts
def default_import_options(self, options: str, ignore: bool = False) -> list:
if options is not None:
opts = options.split()
else:
opts = list()
return opts
def _creds_to_opts(self,creds: dict) -> list:
opts = f"-u{creds['username']} "
opts+=f"-p{creds['password']} "
opts+=f"-P{creds['local_port']} "
opts+=f"-h{creds['local_host']} "
return opts.split() | 0.094866 | 0.064153 |
import os
import argparse
import json
import torch
from torch import nn, autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn.utils import clip_grad_value_
from dataset import KaldiFeatureLabelReader
from model import Net
# [TODO] use toke accuracy as cv metric
def cv(evalset, model):
print("eval:")
total_loss = 0.0
device_type = 'cuda'
device = torch.device(device_type)
ctc_loss = nn.CTCLoss(blank=0, reduction='mean')
model.eval()
num_total_utts = 0
with torch.no_grad():
for batch_id, (k, xs, ys, xlen, ylen) in enumerate(evalset):
xs = xs.to(device)
ys = ys.to(device)
num_utts = ylen.size(0)
num_total_utts += num_utts
outputs = model(xs)
outputs = F.log_softmax(outputs, dim=2)
loss = ctc_loss(outputs.transpose(0, 1), ys, xlen, ylen)
total_loss += loss
return total_loss/num_total_utts
def train(dataset, evalset, epoch_num, model_paras, model_dir, last_model_path=None, use_cuda=False):
# Choose Device
device_type = 'cpu'
if use_cuda:
if torch.cuda.is_available():
print('cuda available')
device_type = 'cuda'
else:
print('no cuda available')
else:
print('not use cuda')
device = torch.device(device_type)
# Load Model
model = Net(model_paras)
if last_model_path:
print("load model from ",last_model_path)
checkpoint = torch.load(last_model_path)
model.load_state_dict(checkpoint['model'])
else:
for param in model.parameters():
torch.nn.init.uniform(param, -0.1, 0.1)
save_model_path = os.path.join(model_dir, 'init.pt')
print('Checkpoint: save init to {}'.format(save_model_path))
state_dict = model.state_dict()
torch.save(
{
'model': state_dict,
'epoch': 0,
}, save_model_path)
model = model.to(device)
# Set Optimizer Type
optim_method = 'adam'
if 'adam' == optim_method:
print('Use Adam')
learning_rate = 1e-4
l2_regularize = 1e-5
optimizer = optim.Adam(model.parameters(),
lr=learning_rate,
weight_decay=l2_regularize)
# sgd not work! It is hard to train the The LSTM weight
if 'sgd' == optim_method:
learning_rate = 4e-4
momentum = 0.9
optimizer = torch.optim.SGD(
model.parameters(), lr=learning_rate, momentum=momentum)
# CTC
use_pytorch_ctc = True
if use_pytorch_ctc:
ctc_loss = nn.CTCLoss(blank=0)
else:
import warpctc_pytorch as warp_ctc
ctc_loss = warp_ctc.CTCLoss()
# Start training
print('Training')
last_epoch_loss = 10000
last_cv_loss = 10000
for epoch in range(epoch_num): # loop over the dataset multiple times
print('epoch {}'.format(epoch))
epoch_loss = 0.0
num_epoch_utts = 0
model.train()
for batch_id, (k, xs, ys, xlen, ylen) in enumerate(dataset):
# Only xs need to device
if use_pytorch_ctc:
xs = xs.to(device)
else:
xs = xs.to(device)
ys = ys.to(device) #add by lixinyu
num_utts = ylen.size(0)
num_epoch_utts += num_utts
# forward
outputs = model(xs)
# ctc_loss need Batch size at axis 1, here use transpose(0, 1) to N,T,D -> T,N,D
if use_pytorch_ctc:
# Also support below ys format, which is same with warp-ctc
# ignore_id=-1
# ys = [y[y != ignore_id] for y in ys] # parse padded ys
# ys = torch.cat(ys).cpu().int() # batch x olen
outputs = F.log_softmax(outputs, dim=2)
loss = ctc_loss(outputs.transpose(0, 1), ys, xlen, ylen)
# buildin CTC use mean as default, so no need to divide by num_utts,
#loss = loss / num_utts
else:
ignore_id = -1
ys = [y[y != ignore_id] for y in ys] # parse padded ys
ys = torch.cat(ys) # batch x olen
outputs = outputs.transpose(0, 1).contiguous()
outputs.requires_grad_(True)
loss = ctc_loss(outputs, ys, xlen, ylen)
loss = torch.mean(loss)
# Reset the gradients
optimizer.zero_grad()
# BackWard
loss.backward()
# Clip gradients to avoid too large value
clip = 5
clip_grad_value_(model.parameters(), clip)
# norm=200
#nn.utils.clip_grad_norm_(model.parameters(), norm)
# Do weight update
optimizer.step()
# Print training set statistics
batch_loss = torch.mean(loss)
epoch_loss += loss
log_interval = 400
if batch_id % log_interval == 0 and batch_id > 0: # print every 2000 mini-batches
print('[epoch {}, batch id {}] batch loss{}'.format(
epoch, batch_id, batch_loss))
epoch_loss = epoch_loss/num_epoch_utts
print('[epoch {}, training loss:{},last training loss:{}'.format(
epoch, epoch_loss, last_epoch_loss))
# Adjust learning rate according cv loss
cv_loss = cv(evalset, model)
# print training set statistics
print('[epoch {}, cv loss:{},last cv loss:{}'.format(
epoch, cv_loss, last_cv_loss))
# decay learning rate
if cv_loss - last_cv_loss > 0:
learning_rate = learning_rate/2
print('adjust learning rate = {}'.format(learning_rate))
for param_group in optimizer.param_groups:
param_group['lr'] = learning_rate
last_cv_loss = cv_loss
last_epoch_loss = epoch_loss
# Save model
save_model_path = os.path.join(model_dir, 'epoch_{}.pt'.format(epoch))
print('Checkpoint: save to checkpoint {}'.format(save_model_path))
state_dict = model.state_dict()
torch.save(
{
'model': state_dict,
'epoch': epoch,
}, save_model_path)
# Stop condition
if learning_rate < 1e-9:
print('learning_rate too small = {}, stop training'.format(learning_rate))
break
# Save final_model
save_model_path = os.path.join(model_dir, 'final.pt')
torch.save(
{
'model': state_dict,
'epoch': epoch,
}, save_model_path)
print('Finished Training')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='training your network')
parser.add_argument('--model_conf', required=True, help='model config')
parser.add_argument('--train_data_dir', required=True,
help='kaldi data dir foramt')
parser.add_argument('--cv_data_dir', required=True,
help='kaldi data dir foramt')
#parser.add_argument('--checkpoint', help='checkpoint model')
parser.add_argument('--model_dir', help='output dir')
parser.add_argument('--model_load_path', type=str, default='',help='model_load_path')
parser.add_argument('--epoch', type=int, default=5 ,help='epoch')
args = parser.parse_args()
# model_paras={
# 'input_dim':120,
# 'hidden_dim':640,
# 'num_layers':4,
# 'output_dim':74 #73 phone + 1 blank
# }
with open(args.model_conf) as fin:
json_string = fin.read()
model_paras = json.loads(json_string)
epoch_num = args.epoch
feat_scp = os.path.join(args.train_data_dir, 'feats.sort.scp')
label_file = os.path.join(args.train_data_dir, 'labels.scp')
utt2spk = os.path.join(args.train_data_dir, 'utt2spk')
cmvn_scp = os.path.join(args.train_data_dir, 'cmvn.scp')
dataset = KaldiFeatureLabelReader(
feat_scp, label_file, utt2spk, cmvn_scp, 8)
feat_scp = os.path.join(args.cv_data_dir, 'feats.sort.scp')
label_file = os.path.join(args.cv_data_dir, 'labels.scp')
utt2spk = os.path.join(args.cv_data_dir, 'utt2spk')
cmvn_scp = os.path.join(args.cv_data_dir, 'cmvn.scp')
evalset = KaldiFeatureLabelReader(
feat_scp, label_file, utt2spk, cmvn_scp, 8)
# model_dir='/export/expts2/chaoyang/e2e/eesen/asr_egs/wsj/pytroch/model2/'
if args.model_load_path=='':
last_model_path=False
else:
last_model_path=args.model_load_path
print("epoch_num",epoch_num)
train(dataset, evalset, epoch_num, model_paras,
args.model_dir, last_model_path, use_cuda=True) | pytorch/train.py | import os
import argparse
import json
import torch
from torch import nn, autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn.utils import clip_grad_value_
from dataset import KaldiFeatureLabelReader
from model import Net
# [TODO] use toke accuracy as cv metric
def cv(evalset, model):
print("eval:")
total_loss = 0.0
device_type = 'cuda'
device = torch.device(device_type)
ctc_loss = nn.CTCLoss(blank=0, reduction='mean')
model.eval()
num_total_utts = 0
with torch.no_grad():
for batch_id, (k, xs, ys, xlen, ylen) in enumerate(evalset):
xs = xs.to(device)
ys = ys.to(device)
num_utts = ylen.size(0)
num_total_utts += num_utts
outputs = model(xs)
outputs = F.log_softmax(outputs, dim=2)
loss = ctc_loss(outputs.transpose(0, 1), ys, xlen, ylen)
total_loss += loss
return total_loss/num_total_utts
def train(dataset, evalset, epoch_num, model_paras, model_dir, last_model_path=None, use_cuda=False):
# Choose Device
device_type = 'cpu'
if use_cuda:
if torch.cuda.is_available():
print('cuda available')
device_type = 'cuda'
else:
print('no cuda available')
else:
print('not use cuda')
device = torch.device(device_type)
# Load Model
model = Net(model_paras)
if last_model_path:
print("load model from ",last_model_path)
checkpoint = torch.load(last_model_path)
model.load_state_dict(checkpoint['model'])
else:
for param in model.parameters():
torch.nn.init.uniform(param, -0.1, 0.1)
save_model_path = os.path.join(model_dir, 'init.pt')
print('Checkpoint: save init to {}'.format(save_model_path))
state_dict = model.state_dict()
torch.save(
{
'model': state_dict,
'epoch': 0,
}, save_model_path)
model = model.to(device)
# Set Optimizer Type
optim_method = 'adam'
if 'adam' == optim_method:
print('Use Adam')
learning_rate = 1e-4
l2_regularize = 1e-5
optimizer = optim.Adam(model.parameters(),
lr=learning_rate,
weight_decay=l2_regularize)
# sgd not work! It is hard to train the The LSTM weight
if 'sgd' == optim_method:
learning_rate = 4e-4
momentum = 0.9
optimizer = torch.optim.SGD(
model.parameters(), lr=learning_rate, momentum=momentum)
# CTC
use_pytorch_ctc = True
if use_pytorch_ctc:
ctc_loss = nn.CTCLoss(blank=0)
else:
import warpctc_pytorch as warp_ctc
ctc_loss = warp_ctc.CTCLoss()
# Start training
print('Training')
last_epoch_loss = 10000
last_cv_loss = 10000
for epoch in range(epoch_num): # loop over the dataset multiple times
print('epoch {}'.format(epoch))
epoch_loss = 0.0
num_epoch_utts = 0
model.train()
for batch_id, (k, xs, ys, xlen, ylen) in enumerate(dataset):
# Only xs need to device
if use_pytorch_ctc:
xs = xs.to(device)
else:
xs = xs.to(device)
ys = ys.to(device) #add by lixinyu
num_utts = ylen.size(0)
num_epoch_utts += num_utts
# forward
outputs = model(xs)
# ctc_loss need Batch size at axis 1, here use transpose(0, 1) to N,T,D -> T,N,D
if use_pytorch_ctc:
# Also support below ys format, which is same with warp-ctc
# ignore_id=-1
# ys = [y[y != ignore_id] for y in ys] # parse padded ys
# ys = torch.cat(ys).cpu().int() # batch x olen
outputs = F.log_softmax(outputs, dim=2)
loss = ctc_loss(outputs.transpose(0, 1), ys, xlen, ylen)
# buildin CTC use mean as default, so no need to divide by num_utts,
#loss = loss / num_utts
else:
ignore_id = -1
ys = [y[y != ignore_id] for y in ys] # parse padded ys
ys = torch.cat(ys) # batch x olen
outputs = outputs.transpose(0, 1).contiguous()
outputs.requires_grad_(True)
loss = ctc_loss(outputs, ys, xlen, ylen)
loss = torch.mean(loss)
# Reset the gradients
optimizer.zero_grad()
# BackWard
loss.backward()
# Clip gradients to avoid too large value
clip = 5
clip_grad_value_(model.parameters(), clip)
# norm=200
#nn.utils.clip_grad_norm_(model.parameters(), norm)
# Do weight update
optimizer.step()
# Print training set statistics
batch_loss = torch.mean(loss)
epoch_loss += loss
log_interval = 400
if batch_id % log_interval == 0 and batch_id > 0: # print every 2000 mini-batches
print('[epoch {}, batch id {}] batch loss{}'.format(
epoch, batch_id, batch_loss))
epoch_loss = epoch_loss/num_epoch_utts
print('[epoch {}, training loss:{},last training loss:{}'.format(
epoch, epoch_loss, last_epoch_loss))
# Adjust learning rate according cv loss
cv_loss = cv(evalset, model)
# print training set statistics
print('[epoch {}, cv loss:{},last cv loss:{}'.format(
epoch, cv_loss, last_cv_loss))
# decay learning rate
if cv_loss - last_cv_loss > 0:
learning_rate = learning_rate/2
print('adjust learning rate = {}'.format(learning_rate))
for param_group in optimizer.param_groups:
param_group['lr'] = learning_rate
last_cv_loss = cv_loss
last_epoch_loss = epoch_loss
# Save model
save_model_path = os.path.join(model_dir, 'epoch_{}.pt'.format(epoch))
print('Checkpoint: save to checkpoint {}'.format(save_model_path))
state_dict = model.state_dict()
torch.save(
{
'model': state_dict,
'epoch': epoch,
}, save_model_path)
# Stop condition
if learning_rate < 1e-9:
print('learning_rate too small = {}, stop training'.format(learning_rate))
break
# Save final_model
save_model_path = os.path.join(model_dir, 'final.pt')
torch.save(
{
'model': state_dict,
'epoch': epoch,
}, save_model_path)
print('Finished Training')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='training your network')
parser.add_argument('--model_conf', required=True, help='model config')
parser.add_argument('--train_data_dir', required=True,
help='kaldi data dir foramt')
parser.add_argument('--cv_data_dir', required=True,
help='kaldi data dir foramt')
#parser.add_argument('--checkpoint', help='checkpoint model')
parser.add_argument('--model_dir', help='output dir')
parser.add_argument('--model_load_path', type=str, default='',help='model_load_path')
parser.add_argument('--epoch', type=int, default=5 ,help='epoch')
args = parser.parse_args()
# model_paras={
# 'input_dim':120,
# 'hidden_dim':640,
# 'num_layers':4,
# 'output_dim':74 #73 phone + 1 blank
# }
with open(args.model_conf) as fin:
json_string = fin.read()
model_paras = json.loads(json_string)
epoch_num = args.epoch
feat_scp = os.path.join(args.train_data_dir, 'feats.sort.scp')
label_file = os.path.join(args.train_data_dir, 'labels.scp')
utt2spk = os.path.join(args.train_data_dir, 'utt2spk')
cmvn_scp = os.path.join(args.train_data_dir, 'cmvn.scp')
dataset = KaldiFeatureLabelReader(
feat_scp, label_file, utt2spk, cmvn_scp, 8)
feat_scp = os.path.join(args.cv_data_dir, 'feats.sort.scp')
label_file = os.path.join(args.cv_data_dir, 'labels.scp')
utt2spk = os.path.join(args.cv_data_dir, 'utt2spk')
cmvn_scp = os.path.join(args.cv_data_dir, 'cmvn.scp')
evalset = KaldiFeatureLabelReader(
feat_scp, label_file, utt2spk, cmvn_scp, 8)
# model_dir='/export/expts2/chaoyang/e2e/eesen/asr_egs/wsj/pytroch/model2/'
if args.model_load_path=='':
last_model_path=False
else:
last_model_path=args.model_load_path
print("epoch_num",epoch_num)
train(dataset, evalset, epoch_num, model_paras,
args.model_dir, last_model_path, use_cuda=True) | 0.556159 | 0.312265 |
from datetime import datetime
from flask_bcrypt import generate_password_hash, check_password_hash
from database import db
class Comment(db.EmbeddedDocument):
content = db.StringField(required=True)
sender = db.ReferenceField('User')
created_date = db.DateTimeField(required=True, default=datetime.now)
class Meta:
collection_name = "comment"
class Card(db.Document):
title = db.StringField(required=True)
content = db.StringField()
start_date = db.DateTimeField()
end_date = db.DateTimeField()
status = db.StringField(required=True, default='received', choices={'received', 'started', 'checked', 'completed'})
assigned_to = db.ListField(db.ReferenceField('User'))
created_by = db.ReferenceField('User')
project = db.ReferenceField('Project')
created_date = db.DateTimeField(required=True, default=datetime.now)
completion_date = db.DateTimeField()
comments = db.ListField(db.EmbeddedDocumentField('Comment'))
class Meta:
collection_name = "card"
class Project(db.Document):
title = db.StringField(required=True, unique=True)
status = db.StringField(required=True, default='active', choices={'active', 'archived'})
created_by = db.ReferenceField('User')
created_date = db.DateTimeField(required=True, default=datetime.now)
cards = db.ListField(db.ReferenceField('Card'), reverse_delete_rule=db.PULL)
class Meta:
collection_name = "project"
strict = False
def find_all(self):
items = self._repo.find_all()
return items
class User(db.Document):
email = db.EmailField(required=True, unique=True)
password = db.StringField(required=True, min_length=6)
projects = db.ListField(db.ReferenceField('Project'), reverse_delete_rule=db.PULL)
cards = db.ListField(db.ReferenceField('Card'), reverse_delete_rule=db.PULL)
assignments = db.ListField(db.ReferenceField('Card'), reverse_delete_rule=db.PULL)
class Meta:
collection_name = "user"
def hash_password(self):
self.password = generate_password_hash(self.password).decode('utf8')
def check_password(self, password):
return check_password_hash(self.password, password)
User.register_delete_rule(Project, 'created_by', db.CASCADE)
User.register_delete_rule(Card, 'created_by', db.CASCADE)
Project.register_delete_rule(Card, 'project', db.CASCADE) | database/models.py |
from datetime import datetime
from flask_bcrypt import generate_password_hash, check_password_hash
from database import db
class Comment(db.EmbeddedDocument):
content = db.StringField(required=True)
sender = db.ReferenceField('User')
created_date = db.DateTimeField(required=True, default=datetime.now)
class Meta:
collection_name = "comment"
class Card(db.Document):
title = db.StringField(required=True)
content = db.StringField()
start_date = db.DateTimeField()
end_date = db.DateTimeField()
status = db.StringField(required=True, default='received', choices={'received', 'started', 'checked', 'completed'})
assigned_to = db.ListField(db.ReferenceField('User'))
created_by = db.ReferenceField('User')
project = db.ReferenceField('Project')
created_date = db.DateTimeField(required=True, default=datetime.now)
completion_date = db.DateTimeField()
comments = db.ListField(db.EmbeddedDocumentField('Comment'))
class Meta:
collection_name = "card"
class Project(db.Document):
title = db.StringField(required=True, unique=True)
status = db.StringField(required=True, default='active', choices={'active', 'archived'})
created_by = db.ReferenceField('User')
created_date = db.DateTimeField(required=True, default=datetime.now)
cards = db.ListField(db.ReferenceField('Card'), reverse_delete_rule=db.PULL)
class Meta:
collection_name = "project"
strict = False
def find_all(self):
items = self._repo.find_all()
return items
class User(db.Document):
email = db.EmailField(required=True, unique=True)
password = db.StringField(required=True, min_length=6)
projects = db.ListField(db.ReferenceField('Project'), reverse_delete_rule=db.PULL)
cards = db.ListField(db.ReferenceField('Card'), reverse_delete_rule=db.PULL)
assignments = db.ListField(db.ReferenceField('Card'), reverse_delete_rule=db.PULL)
class Meta:
collection_name = "user"
def hash_password(self):
self.password = generate_password_hash(self.password).decode('utf8')
def check_password(self, password):
return check_password_hash(self.password, password)
User.register_delete_rule(Project, 'created_by', db.CASCADE)
User.register_delete_rule(Card, 'created_by', db.CASCADE)
Project.register_delete_rule(Card, 'project', db.CASCADE) | 0.569613 | 0.044995 |
import sys
from heapq import heappush, heappop, heapify
BEFORE = True
AFTER = False
def load_num():
line = sys.stdin.readline()
if line == ' ' or line == '\n':
return None
return int(line)
def load_case():
npeople = load_num()
people = []
for p in range(npeople):
people.append(load_num())
return people
def get_cross_candidates(before):
candidates = []
l = len(before)
if l > 3:
t1 = before[1]+before[0]+before[l-1]+before[1]
t2 = before[l-1]+before[0]+before[l-2]+before[0]
if t1 <= t2:
candidates = [
(before[0], before[1]),
(before[0],),
(before[l-2], before[l-1]),
(before[1],)]
else:
candidates = [
(before[0], before[l-2]),
(before[0],),
(before[0], before[l-1]),
(before[0],)]
before.pop()
before.pop()
elif l == 3:
candidates = [
(before[0], before[1]),
(before[0],),
(before[0], before[2])]
before[:] = []
elif l == 2:
candidates = [(before[0], before[1])]
before[:] = []
else:
candidates = [(before[0],)]
before[:] = []
return candidates
def cross_strat(people):
order = []
# Before bridge
before = sorted(people)
# time spent crossing ... for now
seconds = 0
# Iterate until before queue is empty
while len(before):
candidates = get_cross_candidates(before)
for c in candidates:
seconds += max(c)
order.append(c)
return seconds, order
if __name__ == '__main__':
cases = load_num()
for c in range(cases):
sys.stdin.readline()
people = load_case()
seconds, order = cross_strat(people)
print(seconds)
for p in order:
print(" ".join(map(str, p)))
# Empty line after each case except last
if c<cases-1:
print('') | 10037 - Bridge/main.py | import sys
from heapq import heappush, heappop, heapify
BEFORE = True
AFTER = False
def load_num():
line = sys.stdin.readline()
if line == ' ' or line == '\n':
return None
return int(line)
def load_case():
npeople = load_num()
people = []
for p in range(npeople):
people.append(load_num())
return people
def get_cross_candidates(before):
candidates = []
l = len(before)
if l > 3:
t1 = before[1]+before[0]+before[l-1]+before[1]
t2 = before[l-1]+before[0]+before[l-2]+before[0]
if t1 <= t2:
candidates = [
(before[0], before[1]),
(before[0],),
(before[l-2], before[l-1]),
(before[1],)]
else:
candidates = [
(before[0], before[l-2]),
(before[0],),
(before[0], before[l-1]),
(before[0],)]
before.pop()
before.pop()
elif l == 3:
candidates = [
(before[0], before[1]),
(before[0],),
(before[0], before[2])]
before[:] = []
elif l == 2:
candidates = [(before[0], before[1])]
before[:] = []
else:
candidates = [(before[0],)]
before[:] = []
return candidates
def cross_strat(people):
order = []
# Before bridge
before = sorted(people)
# time spent crossing ... for now
seconds = 0
# Iterate until before queue is empty
while len(before):
candidates = get_cross_candidates(before)
for c in candidates:
seconds += max(c)
order.append(c)
return seconds, order
if __name__ == '__main__':
cases = load_num()
for c in range(cases):
sys.stdin.readline()
people = load_case()
seconds, order = cross_strat(people)
print(seconds)
for p in order:
print(" ".join(map(str, p)))
# Empty line after each case except last
if c<cases-1:
print('') | 0.219505 | 0.243465 |
import os
import argparse
import pickle
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential, load_model
from keras.layers import Embedding, LSTM, Dense, Activation, Dropout
from keras.callbacks import EarlyStopping
from keras import backend as k
import numpy as np
from numpy.random import choice
from sklearn.model_selection import train_test_split
from itertools import permutations
from nlp_tools import load_text, clean_text, create_vocabulary, strip_punctuations, tokenize_sentence
def prepare_data(word2id, token_sentences, max_sentence_words = 12 ):
""" Prepares dataset for the model
Args:
word2id: dictionary to convert from words to id
token_sentences: a python array of sentences
max_sentence_words: maximum number of words in a senetnce
Return:
X: Python array of words sequnces
y: Python array of next word in each sequnce
"""
data = []
for sentence in token_sentences:
sentence = strip_punctuations(sentence)
sentence = sentence.lower()
sentence_token_words = sentence.split()
sentence_token_words = ['<BGN>'] + sentence_token_words + ['<EOS>']
sentence_size = min(len(sentence_token_words), max_sentence_words)
for word_index in range(2, sentence_size+1):
token_words = sentence_token_words[: word_index]
num_pads = max_sentence_words - word_index
token_words_padded = ['<PAD>']*num_pads + token_words
token_words_id_padded = [word2id[word] if word in word2id else word2id['<UNK>'] for word in token_words_padded]
data.append(token_words_id_padded)
k.clear_session()
data = np.array(data)
X = data[:, :-1]
y = data[:,-1]
return X, y
def create_model(vocab_size, embedding_dim=40):
""" Creates longuage model using keras
Args:
vocabulary vocab_size
embedding dimmestion
Returns:
model
"""
model = Sequential([
Embedding(input_dim=vocab_size, output_dim=embedding_dim, mask_zero=True),
LSTM(70, dropout=0.00, return_sequences=False),
Dense(vocab_size),
Activation('softmax'),
])
return model
def train_model(model, X_train, X_valid, y_train, y_valid, epochs=100):
""" Trains the keras model
Args:
model: sequential model
X: train dataset
y: train labels
Return:
model: trained model
"""
#callbacks = [EarlyStopping(monitor='val_acc', patience=5)]
callbacks = [ModelCheckpoint('models/checkpoints/model.chkpt'), save_best_only=True, save_weights_only=False)]
model.compile(loss='sparse_categorical_crossentropy',
optimizer='Nadam',
metrics=['accuracy'])
model.fit(X_train, y_train, epochs=epochs, callbacks=callbacks, verbose=2, validation_data=(X_valid,y_valid))
return model
def config_gpu():
""" Configure tensorflow to run on GPU
"""
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.per_process_gpu_memory_fraction = 1
k.tensorflow_backend.set_session(tf.Session(config=config))
def main():
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-n", "--name", type=str, default="English", help="specify the longuage model name")
ap.add_argument("-p", "--path", type=str, default="./data/English.txt", help="Specify the train data path")
ap.add_argument("-c", "--count", type=int, default=16000, help="Specify the maximum number of senetnces to train model")
ap.add_argument("-v", "--vsize", type=int, default=40000, help="Specify the vocabulary size")
ap.add_argument("-l", "--length", type=int, default=15, help="Specify the maximum senetnce length (number of words)")
ap.add_argument("-e", "--epochs", type=int, default=100, help="Specify the number of epoch to train the model")
ap.add_argument("-g", "--gpu", help="Specify to use GPU for training the model", action='store_true')
args = vars(ap.parse_args())
model_name = args["name"]
data_path = args["path"]
num_sentences = args["count"]
vocab_size = args["vsize"]
max_sentence_words = args["length"]
num_epochs = args["epochs"]
use_gpu = args["gpu"]
if use_gpu:
config_gpu()
data = load_text(data_path)
cleaned_data = clean_text(data)
word2id, id2word = create_vocabulary(cleaned_data, vocab_size)
token_senetnces = tokenize_sentence(cleaned_data)
token_senetnces = token_senetnces[:num_sentences]
print("Training longuage model %s using %d sentences" % (model_name, len(token_senetnces)))
X, y = prepare_data(word2id, token_senetnces, max_sentence_words)
model = create_model(vocab_size)
model.summary()
X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.05, random_state=42)
model = train_model(model, X_train, X_valid, y_train, y_valid, num_epochs)
model_path = './models/' + model_name + '_model.h5'
model.save(model_path)
meta_data_path = './models/' + model_name + '_metadata.pickle'
with open(meta_data_path,'wb') as f:
pickle.dump([word2id, id2word], f)
if __name__ == '__main__':
main() | train_lm.py | import os
import argparse
import pickle
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential, load_model
from keras.layers import Embedding, LSTM, Dense, Activation, Dropout
from keras.callbacks import EarlyStopping
from keras import backend as k
import numpy as np
from numpy.random import choice
from sklearn.model_selection import train_test_split
from itertools import permutations
from nlp_tools import load_text, clean_text, create_vocabulary, strip_punctuations, tokenize_sentence
def prepare_data(word2id, token_sentences, max_sentence_words = 12 ):
""" Prepares dataset for the model
Args:
word2id: dictionary to convert from words to id
token_sentences: a python array of sentences
max_sentence_words: maximum number of words in a senetnce
Return:
X: Python array of words sequnces
y: Python array of next word in each sequnce
"""
data = []
for sentence in token_sentences:
sentence = strip_punctuations(sentence)
sentence = sentence.lower()
sentence_token_words = sentence.split()
sentence_token_words = ['<BGN>'] + sentence_token_words + ['<EOS>']
sentence_size = min(len(sentence_token_words), max_sentence_words)
for word_index in range(2, sentence_size+1):
token_words = sentence_token_words[: word_index]
num_pads = max_sentence_words - word_index
token_words_padded = ['<PAD>']*num_pads + token_words
token_words_id_padded = [word2id[word] if word in word2id else word2id['<UNK>'] for word in token_words_padded]
data.append(token_words_id_padded)
k.clear_session()
data = np.array(data)
X = data[:, :-1]
y = data[:,-1]
return X, y
def create_model(vocab_size, embedding_dim=40):
""" Creates longuage model using keras
Args:
vocabulary vocab_size
embedding dimmestion
Returns:
model
"""
model = Sequential([
Embedding(input_dim=vocab_size, output_dim=embedding_dim, mask_zero=True),
LSTM(70, dropout=0.00, return_sequences=False),
Dense(vocab_size),
Activation('softmax'),
])
return model
def train_model(model, X_train, X_valid, y_train, y_valid, epochs=100):
""" Trains the keras model
Args:
model: sequential model
X: train dataset
y: train labels
Return:
model: trained model
"""
#callbacks = [EarlyStopping(monitor='val_acc', patience=5)]
callbacks = [ModelCheckpoint('models/checkpoints/model.chkpt'), save_best_only=True, save_weights_only=False)]
model.compile(loss='sparse_categorical_crossentropy',
optimizer='Nadam',
metrics=['accuracy'])
model.fit(X_train, y_train, epochs=epochs, callbacks=callbacks, verbose=2, validation_data=(X_valid,y_valid))
return model
def config_gpu():
""" Configure tensorflow to run on GPU
"""
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.per_process_gpu_memory_fraction = 1
k.tensorflow_backend.set_session(tf.Session(config=config))
def main():
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-n", "--name", type=str, default="English", help="specify the longuage model name")
ap.add_argument("-p", "--path", type=str, default="./data/English.txt", help="Specify the train data path")
ap.add_argument("-c", "--count", type=int, default=16000, help="Specify the maximum number of senetnces to train model")
ap.add_argument("-v", "--vsize", type=int, default=40000, help="Specify the vocabulary size")
ap.add_argument("-l", "--length", type=int, default=15, help="Specify the maximum senetnce length (number of words)")
ap.add_argument("-e", "--epochs", type=int, default=100, help="Specify the number of epoch to train the model")
ap.add_argument("-g", "--gpu", help="Specify to use GPU for training the model", action='store_true')
args = vars(ap.parse_args())
model_name = args["name"]
data_path = args["path"]
num_sentences = args["count"]
vocab_size = args["vsize"]
max_sentence_words = args["length"]
num_epochs = args["epochs"]
use_gpu = args["gpu"]
if use_gpu:
config_gpu()
data = load_text(data_path)
cleaned_data = clean_text(data)
word2id, id2word = create_vocabulary(cleaned_data, vocab_size)
token_senetnces = tokenize_sentence(cleaned_data)
token_senetnces = token_senetnces[:num_sentences]
print("Training longuage model %s using %d sentences" % (model_name, len(token_senetnces)))
X, y = prepare_data(word2id, token_senetnces, max_sentence_words)
model = create_model(vocab_size)
model.summary()
X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.05, random_state=42)
model = train_model(model, X_train, X_valid, y_train, y_valid, num_epochs)
model_path = './models/' + model_name + '_model.h5'
model.save(model_path)
meta_data_path = './models/' + model_name + '_metadata.pickle'
with open(meta_data_path,'wb') as f:
pickle.dump([word2id, id2word], f)
if __name__ == '__main__':
main() | 0.777596 | 0.343067 |
from datetime import datetime
from django.core.validators import MaxValueValidator
from django.db import models
from django.test import TestCase
from freezegun import freeze_time
from conditioner.conditions.dates import DayOfMonthCondition, DayOfWeekCondition
from conditioner.base import BaseCronCondition
from conditioner.tests.conditions.factories import DayOfMonthConditionFactory, DayOfWeekConditionFactory
class DayOfMonthConditionTestCase(TestCase):
"""
Test `conditioner.conditions.dates.DayOfMonthCondition` model
"""
def setUp(self):
super().setUp()
self.model = DayOfMonthCondition
self.instance = DayOfMonthConditionFactory()
def test_model_inheritance(self):
"""Test model inheritance"""
self.assertIsInstance(self.instance, BaseCronCondition)
def test_model_day_field(self):
"""Test model 'day' field"""
field = self.model._meta.get_field('day')
self.assertIsInstance(field, models.PositiveSmallIntegerField)
self.assertEqual(field.verbose_name, 'day of the month')
self.assertEqual(field.help_text, "Action will occur every month on that day.")
def test_model_day_field_validators(self):
"""Test model 'day' field validators"""
field = self.instance._meta.get_field('day')
validator = field.validators[0]
self.assertIsInstance(validator, MaxValueValidator)
self.assertEqual(validator.limit_value, 31)
def test_model_meta_attributes(self):
"""Test model meta attributes"""
meta = self.model._meta
self.assertEqual(meta.verbose_name, 'day of month condition')
self.assertEqual(meta.verbose_name_plural, 'day of month conditions')
def test_model_is_met_method(self):
"""Test model `is_met()` method"""
instance = DayOfMonthConditionFactory(day=2)
# Wrong day
with freeze_time('2016-01-01'):
self.assertFalse(instance.is_met())
# Correct day
with freeze_time('2016-01-02'):
self.assertTrue(instance.is_met())
instance.last_executed = datetime(2016, 1, 2)
instance.save()
# Correct day, but the same date as 'last_executed'
with freeze_time('2016-01-02'):
self.assertFalse(instance.is_met())
# Wrong day
with freeze_time('2016-02-01'):
self.assertFalse(instance.is_met())
# Correct day
with freeze_time('2016-02-02'):
self.assertTrue(instance.is_met())
def test_model_str_method(self):
"""Test model `__str__` method"""
self.assertIn(str(self.instance.day), str(self.instance))
class DayOfWeekConditionTestCase(TestCase):
"""
Test `conditioner.conditions.dates.DayOfWeekCondition` model
"""
def setUp(self):
super().setUp()
self.model = DayOfWeekCondition
self.instance = DayOfWeekConditionFactory()
def test_model_inheritance(self):
"""Test model inheritance"""
self.assertIsInstance(self.instance, BaseCronCondition)
def test_model_weekday_field(self):
"""Test model 'weekday' field"""
field = self.model._meta.get_field('weekday')
self.assertIsInstance(field, models.PositiveSmallIntegerField)
self.assertEqual(field.verbose_name, 'day of the week')
self.assertEqual(field.choices, self.model.WEEKDAY_CHOICES)
self.assertEqual(field.help_text, "Action will occur every week on that day.")
def test_model_meta_attributes(self):
"""Test model meta attributes"""
meta = self.model._meta
self.assertEqual(meta.verbose_name, 'day of week condition')
self.assertEqual(meta.verbose_name_plural, 'day of week conditions')
def test_model_is_met_method(self):
"""Test model `is_met()` method"""
instance = DayOfWeekConditionFactory(weekday=7)
# Wrong weekday (January 1 2007 is Monday)
with freeze_time('2007-01-01'):
self.assertFalse(instance.is_met())
# Correct weekday
with freeze_time('2007-01-07'):
self.assertTrue(instance.is_met())
instance.last_executed = datetime(2007, 1, 7)
instance.save()
# Correct weekday, but the same date as 'last_executed'
with freeze_time('2007-01-07'):
self.assertFalse(instance.is_met())
# Wrong weekday
with freeze_time('2007-01-10'):
self.assertFalse(instance.is_met())
# Correct weekday
with freeze_time('2007-01-14'):
self.assertTrue(instance.is_met())
def test_model_str_method(self):
"""Test model `__str__` method"""
self.assertIn(self.instance.get_weekday_display(), str(self.instance)) | conditioner/tests/conditions/test_dates.py | from datetime import datetime
from django.core.validators import MaxValueValidator
from django.db import models
from django.test import TestCase
from freezegun import freeze_time
from conditioner.conditions.dates import DayOfMonthCondition, DayOfWeekCondition
from conditioner.base import BaseCronCondition
from conditioner.tests.conditions.factories import DayOfMonthConditionFactory, DayOfWeekConditionFactory
class DayOfMonthConditionTestCase(TestCase):
"""
Test `conditioner.conditions.dates.DayOfMonthCondition` model
"""
def setUp(self):
super().setUp()
self.model = DayOfMonthCondition
self.instance = DayOfMonthConditionFactory()
def test_model_inheritance(self):
"""Test model inheritance"""
self.assertIsInstance(self.instance, BaseCronCondition)
def test_model_day_field(self):
"""Test model 'day' field"""
field = self.model._meta.get_field('day')
self.assertIsInstance(field, models.PositiveSmallIntegerField)
self.assertEqual(field.verbose_name, 'day of the month')
self.assertEqual(field.help_text, "Action will occur every month on that day.")
def test_model_day_field_validators(self):
"""Test model 'day' field validators"""
field = self.instance._meta.get_field('day')
validator = field.validators[0]
self.assertIsInstance(validator, MaxValueValidator)
self.assertEqual(validator.limit_value, 31)
def test_model_meta_attributes(self):
"""Test model meta attributes"""
meta = self.model._meta
self.assertEqual(meta.verbose_name, 'day of month condition')
self.assertEqual(meta.verbose_name_plural, 'day of month conditions')
def test_model_is_met_method(self):
"""Test model `is_met()` method"""
instance = DayOfMonthConditionFactory(day=2)
# Wrong day
with freeze_time('2016-01-01'):
self.assertFalse(instance.is_met())
# Correct day
with freeze_time('2016-01-02'):
self.assertTrue(instance.is_met())
instance.last_executed = datetime(2016, 1, 2)
instance.save()
# Correct day, but the same date as 'last_executed'
with freeze_time('2016-01-02'):
self.assertFalse(instance.is_met())
# Wrong day
with freeze_time('2016-02-01'):
self.assertFalse(instance.is_met())
# Correct day
with freeze_time('2016-02-02'):
self.assertTrue(instance.is_met())
def test_model_str_method(self):
"""Test model `__str__` method"""
self.assertIn(str(self.instance.day), str(self.instance))
class DayOfWeekConditionTestCase(TestCase):
"""
Test `conditioner.conditions.dates.DayOfWeekCondition` model
"""
def setUp(self):
super().setUp()
self.model = DayOfWeekCondition
self.instance = DayOfWeekConditionFactory()
def test_model_inheritance(self):
"""Test model inheritance"""
self.assertIsInstance(self.instance, BaseCronCondition)
def test_model_weekday_field(self):
"""Test model 'weekday' field"""
field = self.model._meta.get_field('weekday')
self.assertIsInstance(field, models.PositiveSmallIntegerField)
self.assertEqual(field.verbose_name, 'day of the week')
self.assertEqual(field.choices, self.model.WEEKDAY_CHOICES)
self.assertEqual(field.help_text, "Action will occur every week on that day.")
def test_model_meta_attributes(self):
"""Test model meta attributes"""
meta = self.model._meta
self.assertEqual(meta.verbose_name, 'day of week condition')
self.assertEqual(meta.verbose_name_plural, 'day of week conditions')
def test_model_is_met_method(self):
"""Test model `is_met()` method"""
instance = DayOfWeekConditionFactory(weekday=7)
# Wrong weekday (January 1 2007 is Monday)
with freeze_time('2007-01-01'):
self.assertFalse(instance.is_met())
# Correct weekday
with freeze_time('2007-01-07'):
self.assertTrue(instance.is_met())
instance.last_executed = datetime(2007, 1, 7)
instance.save()
# Correct weekday, but the same date as 'last_executed'
with freeze_time('2007-01-07'):
self.assertFalse(instance.is_met())
# Wrong weekday
with freeze_time('2007-01-10'):
self.assertFalse(instance.is_met())
# Correct weekday
with freeze_time('2007-01-14'):
self.assertTrue(instance.is_met())
def test_model_str_method(self):
"""Test model `__str__` method"""
self.assertIn(self.instance.get_weekday_display(), str(self.instance)) | 0.857664 | 0.507385 |
import numpy as np
def calculate_factorial(x: int) -> int:
if x == 1:
return 1
else:
return x * calculate_factorial(x - 1)
def p1(k: int) -> str:
answer_string = ""
for x in range(k, 0, -1):
factorial = calculate_factorial(x)
if x == k:
answer_string = str(factorial)
else:
answer_string = answer_string + "," + str(factorial)
return answer_string
def p2_a(x: list, y: list) -> list:
y.sort(reverse=True)
del y[-1]
return y
def p2_b(x: list, y: list) -> list:
x.reverse()
return x
def p2_c(x: list, y: list) -> list:
new_list = list(set(x + y))
new_list.sort(reverse=False)
return new_list
def p2_d(x: list, y: list) -> list:
return [x, y]
def p3_a(x: set, y: set, z: set) -> set:
union = x.union(y, z)
return union
def p3_b(x: set, y: set, z: set) -> set:
intersection = x.intersection(y, z)
return intersection
def p3_c(x: set, y: set, z: set) -> set:
elements_in_x_only = x.difference(y.union(z))
elements_in_y_only = y.difference(x.union(z))
elements_in_z_only = z.difference(x.union(y))
elements_only_in_single_set = elements_in_x_only.union(elements_in_y_only, elements_in_z_only)
return elements_only_in_single_set
def p4_a() -> np.array:
l, b = 5, 5
A = np.array([[0 for j in range(0, l, 1)] for i in range(0, b, 1)])
for i in range(0, 5, 1):
for j in range(0, 5, 1):
if (i == 0 or i == 4) or (j == 0 or j == 4):
A[i][j] = 1
elif i == 2 and j == 2:
A[i][j] = 2
return A
def is_there_a_knight(x: int) -> bool:
if x == 1:
return True
else:
return False
def valid_position_for_knight(i: int, j: int) -> bool:
if (0 <= i) and (i < 5) and (0 <= j) and (j < 5):
return True
else:
return False
def knight_attacking_the_white_pawn(x: np.array, i: int, j: int) -> bool:
for row_change in [2, 1, -1, -2]:
if row_change in [1, -1]:
for column_change in [2, -2]:
if valid_position_for_knight(i + row_change, j + column_change) and \
x[i + row_change][j + column_change] == 2:
return True
elif row_change in [2, -2]:
for column_change in [1, -1]:
if valid_position_for_knight(i + row_change, j + column_change) and \
x[i + row_change][j + column_change] == 2:
return True
def p4_b(x: np.array) -> list:
threaten_the_white_pawn = []
for i in range(0, 5, 1):
for j in range(0, 5, 1):
if is_there_a_knight(x[i][j]) and knight_attacking_the_white_pawn(x, i, j):
threaten_the_white_pawn.append((i, j))
return threaten_the_white_pawn
def p5_a(x: dict) -> int:
no_of_isolated_notes = 0
for key in x.keys():
if len(x[key]) == 0:
no_of_isolated_notes += 1
return no_of_isolated_notes
def p5_b(x: dict) -> int:
return len(x) - p5_a(x)
def p5_c(x: dict) -> list:
edges = []
for starting_node in x.keys():
for ending_node in x[starting_node]:
if (starting_node, ending_node) in edges or (ending_node, starting_node) in edges:
pass
else:
edges.append((starting_node, ending_node))
return edges
def p5_d(x: dict) -> np.array:
l, b = len(x), len(x)
adj_matrix = np.array([[0 for j in range(0, l, 1)] for i in range(0, b, 1)])
index = 0
indexed_dict = {}
for keys in x.keys():
indexed_dict[keys] = index
index += 1
for starting_node in x.keys():
for ending_node in x[starting_node]:
adj_matrix[indexed_dict[starting_node]][indexed_dict[ending_node]] = 1
return adj_matrix
class PriorityQueue(object):
def __init__(self):
self.market_price = {'apple': 5.0, 'banana': 4.5, 'carrot': 3.3, 'kiwi': 7.4, 'orange': 5.0, 'mango': 9.1,
'pineapple': 9.1}
self.priority_queue = []
def push(self, x):
self.priority_queue.append((x, self.market_price[x]))
self.priority_queue.sort(key=lambda element: element[1], reverse=True)
return self.priority_queue
def pop(self):
return self.priority_queue.pop(0)[0]
def is_empty(self):
if len(self.priority_queue) == 0:
return True
else:
return False
if __name__ == '__main__':
print(p1(k=8))
print('-----------------------------')
print(p2_a(x=[], y=[1, 3, 5]))
print(p2_b(x=[2, 4, 6], y=[]))
print(p2_c(x=[1, 3, 5, 7], y=[1, 2, 5, 6]))
print(p2_d(x=[1, 3, 5, 7], y=[1, 2, 5, 6]))
print('------------------------------')
print(p3_a(x={1, 3, 5, 7}, y={1, 2, 5, 6}, z={7, 8, 9, 1}))
print(p3_b(x={1, 3, 5, 7}, y={1, 2, 5, 6}, z={7, 8, 9, 1}))
print(p3_c(x={1, 3, 5, 7}, y={1, 2, 5, 6}, z={7, 8, 9, 1}))
print('------------------------------')
print(p4_a())
print(p4_b(p4_a()))
print('------------------------------')
graph = {
'A': ['D', 'E'],
'B': ['E', 'F'],
'C': ['E'],
'D': ['A', 'E'],
'E': ['A', 'B', 'C', 'D'],
'F': ['B'],
'G': []
}
print(p5_a(graph))
print(p5_b(graph))
print(p5_c(graph))
print(p5_d(graph))
print('------------------------------')
pq = PriorityQueue()
pq.push('apple')
pq.push('kiwi')
pq.push('orange')
while not pq.is_empty():
print(pq.pop()) | Homework1/homework1.py | import numpy as np
def calculate_factorial(x: int) -> int:
if x == 1:
return 1
else:
return x * calculate_factorial(x - 1)
def p1(k: int) -> str:
answer_string = ""
for x in range(k, 0, -1):
factorial = calculate_factorial(x)
if x == k:
answer_string = str(factorial)
else:
answer_string = answer_string + "," + str(factorial)
return answer_string
def p2_a(x: list, y: list) -> list:
y.sort(reverse=True)
del y[-1]
return y
def p2_b(x: list, y: list) -> list:
x.reverse()
return x
def p2_c(x: list, y: list) -> list:
new_list = list(set(x + y))
new_list.sort(reverse=False)
return new_list
def p2_d(x: list, y: list) -> list:
return [x, y]
def p3_a(x: set, y: set, z: set) -> set:
union = x.union(y, z)
return union
def p3_b(x: set, y: set, z: set) -> set:
intersection = x.intersection(y, z)
return intersection
def p3_c(x: set, y: set, z: set) -> set:
elements_in_x_only = x.difference(y.union(z))
elements_in_y_only = y.difference(x.union(z))
elements_in_z_only = z.difference(x.union(y))
elements_only_in_single_set = elements_in_x_only.union(elements_in_y_only, elements_in_z_only)
return elements_only_in_single_set
def p4_a() -> np.array:
l, b = 5, 5
A = np.array([[0 for j in range(0, l, 1)] for i in range(0, b, 1)])
for i in range(0, 5, 1):
for j in range(0, 5, 1):
if (i == 0 or i == 4) or (j == 0 or j == 4):
A[i][j] = 1
elif i == 2 and j == 2:
A[i][j] = 2
return A
def is_there_a_knight(x: int) -> bool:
if x == 1:
return True
else:
return False
def valid_position_for_knight(i: int, j: int) -> bool:
if (0 <= i) and (i < 5) and (0 <= j) and (j < 5):
return True
else:
return False
def knight_attacking_the_white_pawn(x: np.array, i: int, j: int) -> bool:
for row_change in [2, 1, -1, -2]:
if row_change in [1, -1]:
for column_change in [2, -2]:
if valid_position_for_knight(i + row_change, j + column_change) and \
x[i + row_change][j + column_change] == 2:
return True
elif row_change in [2, -2]:
for column_change in [1, -1]:
if valid_position_for_knight(i + row_change, j + column_change) and \
x[i + row_change][j + column_change] == 2:
return True
def p4_b(x: np.array) -> list:
threaten_the_white_pawn = []
for i in range(0, 5, 1):
for j in range(0, 5, 1):
if is_there_a_knight(x[i][j]) and knight_attacking_the_white_pawn(x, i, j):
threaten_the_white_pawn.append((i, j))
return threaten_the_white_pawn
def p5_a(x: dict) -> int:
no_of_isolated_notes = 0
for key in x.keys():
if len(x[key]) == 0:
no_of_isolated_notes += 1
return no_of_isolated_notes
def p5_b(x: dict) -> int:
return len(x) - p5_a(x)
def p5_c(x: dict) -> list:
edges = []
for starting_node in x.keys():
for ending_node in x[starting_node]:
if (starting_node, ending_node) in edges or (ending_node, starting_node) in edges:
pass
else:
edges.append((starting_node, ending_node))
return edges
def p5_d(x: dict) -> np.array:
l, b = len(x), len(x)
adj_matrix = np.array([[0 for j in range(0, l, 1)] for i in range(0, b, 1)])
index = 0
indexed_dict = {}
for keys in x.keys():
indexed_dict[keys] = index
index += 1
for starting_node in x.keys():
for ending_node in x[starting_node]:
adj_matrix[indexed_dict[starting_node]][indexed_dict[ending_node]] = 1
return adj_matrix
class PriorityQueue(object):
def __init__(self):
self.market_price = {'apple': 5.0, 'banana': 4.5, 'carrot': 3.3, 'kiwi': 7.4, 'orange': 5.0, 'mango': 9.1,
'pineapple': 9.1}
self.priority_queue = []
def push(self, x):
self.priority_queue.append((x, self.market_price[x]))
self.priority_queue.sort(key=lambda element: element[1], reverse=True)
return self.priority_queue
def pop(self):
return self.priority_queue.pop(0)[0]
def is_empty(self):
if len(self.priority_queue) == 0:
return True
else:
return False
if __name__ == '__main__':
print(p1(k=8))
print('-----------------------------')
print(p2_a(x=[], y=[1, 3, 5]))
print(p2_b(x=[2, 4, 6], y=[]))
print(p2_c(x=[1, 3, 5, 7], y=[1, 2, 5, 6]))
print(p2_d(x=[1, 3, 5, 7], y=[1, 2, 5, 6]))
print('------------------------------')
print(p3_a(x={1, 3, 5, 7}, y={1, 2, 5, 6}, z={7, 8, 9, 1}))
print(p3_b(x={1, 3, 5, 7}, y={1, 2, 5, 6}, z={7, 8, 9, 1}))
print(p3_c(x={1, 3, 5, 7}, y={1, 2, 5, 6}, z={7, 8, 9, 1}))
print('------------------------------')
print(p4_a())
print(p4_b(p4_a()))
print('------------------------------')
graph = {
'A': ['D', 'E'],
'B': ['E', 'F'],
'C': ['E'],
'D': ['A', 'E'],
'E': ['A', 'B', 'C', 'D'],
'F': ['B'],
'G': []
}
print(p5_a(graph))
print(p5_b(graph))
print(p5_c(graph))
print(p5_d(graph))
print('------------------------------')
pq = PriorityQueue()
pq.push('apple')
pq.push('kiwi')
pq.push('orange')
while not pq.is_empty():
print(pq.pop()) | 0.347537 | 0.639441 |
import unittest
from pymath.expression import Expression
from pymath.fraction import Fraction
from pymath.generic import first_elem
from pymath.renders import txt_render
class TestExpression(unittest.TestCase):
"""Testing functions from pymath.expression"""
def test_init_from_str(self):
exp = Expression("2 + 3")
self.assertEqual(exp.infix_tokens, [2, "+", 3])
self.assertEqual(exp.postfix_tokens, [2, 3, "+"])
def test_init_from_exp(self):
pass
def test_infix_tokens(self):
pass
def test_postfix_tokens(self):
pass
def test_str2tokens_big_num(self):
exp = "123 + 3"
tok = Expression.str2tokens(exp)
self.assertEqual(tok, [123, "+", 3])
def test_str2tokens_beg_minus(self):
exp = "-123 + 3"
tok = Expression.str2tokens(exp)
self.assertEqual(tok, [-123, "+", 3])
def test_str2tokens_time_lack(self):
exp = "(-3)(2)"
tok = Expression.str2tokens(exp)
self.assertEqual(tok, ["(", -3, ")", "*","(", 2, ")" ])
def test_str2tokens_time_lack2(self):
exp = "-3(2)"
tok = Expression.str2tokens(exp)
self.assertEqual(tok, [-3, "*","(", 2, ")" ])
def test_str2tokens_error_float(self):
exp = "1 + 1.3"
self.assertRaises(ValueError, Expression.str2tokens, exp)
def test_str2tokens_error(self):
exp = "1 + $"
self.assertRaises(ValueError, Expression.str2tokens, exp)
def test_doMath(self):
ops = [\
{"op": ("+", 1 , 2), "res" : 3}, \
{"op": ("-", 1 , 2), "res" : -1}, \
{"op": ("*", 1 , 2), "res" : 2}, \
{"op": ("/", 1 , 2), "res" : Fraction(1,2)}, \
{"op": ("^", 1 , 2), "res" : 1}, \
]
for op in ops:
res = first_elem(Expression.doMath(*op["op"]))
self.assertAlmostEqual(res, op["res"])
def test_isNumber(self):
pass
def test_isOperator(self):
pass
def test_simplify_frac(self):
exp = Expression("1/2 - 4")
steps = ["[1, 2, '/', 4, '-']", \
"[< Fraction 1 / 2>, 4, '-']", \
"[1, 1, '*', 2, 1, '*', '/', 4, 2, '*', 1, 2, '*', '/', '-']", \
"[1, 8, '-', 2, '/']", \
'[< Fraction -7 / 2>]']
self.assertEqual(steps, list(exp.simplify()))
if __name__ == '__main__':
unittest.main()
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del | test/test_expression.py |
import unittest
from pymath.expression import Expression
from pymath.fraction import Fraction
from pymath.generic import first_elem
from pymath.renders import txt_render
class TestExpression(unittest.TestCase):
"""Testing functions from pymath.expression"""
def test_init_from_str(self):
exp = Expression("2 + 3")
self.assertEqual(exp.infix_tokens, [2, "+", 3])
self.assertEqual(exp.postfix_tokens, [2, 3, "+"])
def test_init_from_exp(self):
pass
def test_infix_tokens(self):
pass
def test_postfix_tokens(self):
pass
def test_str2tokens_big_num(self):
exp = "123 + 3"
tok = Expression.str2tokens(exp)
self.assertEqual(tok, [123, "+", 3])
def test_str2tokens_beg_minus(self):
exp = "-123 + 3"
tok = Expression.str2tokens(exp)
self.assertEqual(tok, [-123, "+", 3])
def test_str2tokens_time_lack(self):
exp = "(-3)(2)"
tok = Expression.str2tokens(exp)
self.assertEqual(tok, ["(", -3, ")", "*","(", 2, ")" ])
def test_str2tokens_time_lack2(self):
exp = "-3(2)"
tok = Expression.str2tokens(exp)
self.assertEqual(tok, [-3, "*","(", 2, ")" ])
def test_str2tokens_error_float(self):
exp = "1 + 1.3"
self.assertRaises(ValueError, Expression.str2tokens, exp)
def test_str2tokens_error(self):
exp = "1 + $"
self.assertRaises(ValueError, Expression.str2tokens, exp)
def test_doMath(self):
ops = [\
{"op": ("+", 1 , 2), "res" : 3}, \
{"op": ("-", 1 , 2), "res" : -1}, \
{"op": ("*", 1 , 2), "res" : 2}, \
{"op": ("/", 1 , 2), "res" : Fraction(1,2)}, \
{"op": ("^", 1 , 2), "res" : 1}, \
]
for op in ops:
res = first_elem(Expression.doMath(*op["op"]))
self.assertAlmostEqual(res, op["res"])
def test_isNumber(self):
pass
def test_isOperator(self):
pass
def test_simplify_frac(self):
exp = Expression("1/2 - 4")
steps = ["[1, 2, '/', 4, '-']", \
"[< Fraction 1 / 2>, 4, '-']", \
"[1, 1, '*', 2, 1, '*', '/', 4, 2, '*', 1, 2, '*', '/', '-']", \
"[1, 8, '-', 2, '/']", \
'[< Fraction -7 / 2>]']
self.assertEqual(steps, list(exp.simplify()))
if __name__ == '__main__':
unittest.main()
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del | 0.53048 | 0.701575 |
def extractWuxiaNation(item):
"""
'WuxiaNation'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if 'Announcements' in item['tags']:
return None
tagmap = [
('Mysterious Job Called Oda Nobunaga', 'Mysterious Job Called Oda Nobunaga', 'translated'),
('The Lame Daoist Priest', 'The Lame Daoist Priest', 'translated'),
('I Grow Stronger by Dreaming', 'I Grow Stronger by Dreaming', 'translated'),
('World of Warcraft: Foreign Realm Domination', 'World of Warcraft: Foreign Realm Domination', 'translated'),
('Storm in the Wilderness', 'Storm in the Wilderness', 'translated'),
('Great Dao Commander', 'Great Dao Commander', 'translated'),
('A Stern Devil', 'A Stern Devil', 'translated'),
('Song of Heroes', 'Song of Heroes', 'translated'),
('the dark king', 'The Dark King', 'translated'),
('age of heroes', 'Age of Heroes', 'translated'),
('Conquer God, Asura, and 1000 Beauties', 'Conquer God, Asura, and 1000 Beauties', 'translated'),
('The Solitary Sword Sovereign', 'The Solitary Sword Sovereign', 'translated'),
('lord shadow', 'Lord Shadow', 'translated'),
('In Different World With Naruto System', 'In Different World With Naruto System', 'translated'),
('<NAME>', '<NAME>', 'translated'),
('7 Kingdoms of Midgard', '7 Kingdoms of Midgard', 'translated'),
('MOTDN', 'Monarch of the Dark Nights', 'translated'),
('Hisshou Dungeon Unei Houhou', 'Hisshou Dungeon Unei Houhou', 'translated'),
('nagabumi', 'Nagabumi', 'translated'),
('Special Forces King', 'Special Forces King', 'translated'),
('Immortal Ape King', 'Immortal Ape King', 'translated'),
('Law of the Devil', 'Law of the Devil', 'translated'),
('Age of Adventure', 'Age of Adventure', 'translated'),
('Nine Yang Sword Saint', 'Nine Yang Sword Saint', 'translated'),
('warlord', 'Warlord', 'translated'),
('MRRG', 'My Reality is a Romance Game', 'translated'),
('eth2', 'Evolution Theory of the Hunter', 'translated'),
('eth', 'Evolution Theory of the Hunter', 'translated'),
('CoR', 'Cohen of the Rebellion', 'translated'),
('The Assassin\'s Apprentice', 'The Assassin\'s Apprentice', 'translated'),
('Immortal Ascension Tower', 'Immortal Ascension Tower', 'oel'),
('Aurora God', 'Aurora God', 'oel'),
('lord shadow', 'lord shadow', 'oel'),
('Pathless Origins: Bane of the Gods', 'Pathless Origins: Bane of the Gods', 'oel'),
('Novus Gaia', 'Age of Heroes: Novus Gaia', 'oel'),
('House of Omen', 'House of Omen', 'oel'),
('Samsara Breaker', 'Samsara Breaker', 'oel'),
('Venture with Anime system', 'Venture with Anime system', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False | WebMirror/management/rss_parser_funcs/feed_parse_extractWuxiaNation.py | def extractWuxiaNation(item):
"""
'WuxiaNation'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if 'Announcements' in item['tags']:
return None
tagmap = [
('Mysterious Job Called Oda Nobunaga', 'Mysterious Job Called Oda Nobunaga', 'translated'),
('The Lame Daoist Priest', 'The Lame Daoist Priest', 'translated'),
('I Grow Stronger by Dreaming', 'I Grow Stronger by Dreaming', 'translated'),
('World of Warcraft: Foreign Realm Domination', 'World of Warcraft: Foreign Realm Domination', 'translated'),
('Storm in the Wilderness', 'Storm in the Wilderness', 'translated'),
('Great Dao Commander', 'Great Dao Commander', 'translated'),
('A Stern Devil', 'A Stern Devil', 'translated'),
('Song of Heroes', 'Song of Heroes', 'translated'),
('the dark king', 'The Dark King', 'translated'),
('age of heroes', 'Age of Heroes', 'translated'),
('Conquer God, Asura, and 1000 Beauties', 'Conquer God, Asura, and 1000 Beauties', 'translated'),
('The Solitary Sword Sovereign', 'The Solitary Sword Sovereign', 'translated'),
('lord shadow', 'Lord Shadow', 'translated'),
('In Different World With Naruto System', 'In Different World With Naruto System', 'translated'),
('<NAME>', '<NAME>', 'translated'),
('7 Kingdoms of Midgard', '7 Kingdoms of Midgard', 'translated'),
('MOTDN', 'Monarch of the Dark Nights', 'translated'),
('Hisshou Dungeon Unei Houhou', 'Hisshou Dungeon Unei Houhou', 'translated'),
('nagabumi', 'Nagabumi', 'translated'),
('Special Forces King', 'Special Forces King', 'translated'),
('Immortal Ape King', 'Immortal Ape King', 'translated'),
('Law of the Devil', 'Law of the Devil', 'translated'),
('Age of Adventure', 'Age of Adventure', 'translated'),
('Nine Yang Sword Saint', 'Nine Yang Sword Saint', 'translated'),
('warlord', 'Warlord', 'translated'),
('MRRG', 'My Reality is a Romance Game', 'translated'),
('eth2', 'Evolution Theory of the Hunter', 'translated'),
('eth', 'Evolution Theory of the Hunter', 'translated'),
('CoR', 'Cohen of the Rebellion', 'translated'),
('The Assassin\'s Apprentice', 'The Assassin\'s Apprentice', 'translated'),
('Immortal Ascension Tower', 'Immortal Ascension Tower', 'oel'),
('Aurora God', 'Aurora God', 'oel'),
('lord shadow', 'lord shadow', 'oel'),
('Pathless Origins: Bane of the Gods', 'Pathless Origins: Bane of the Gods', 'oel'),
('Novus Gaia', 'Age of Heroes: Novus Gaia', 'oel'),
('House of Omen', 'House of Omen', 'oel'),
('Samsara Breaker', 'Samsara Breaker', 'oel'),
('Venture with Anime system', 'Venture with Anime system', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False | 0.309858 | 0.237963 |
import torch
import torch.nn as nn
# built-in
from math import sqrt
import functools
# Based on implementation from <NAME> (2016)
class ResNet(nn.Module):
def __init__(self, num_blocks=7, nc32=32, nc16=64, nc8=128):
"""
:param num_blocks: the number of resnet blocks per stage. There are 3 stages, for feature map width 32, 16, 8.
Total number of layers is 6 * num_blocks + 2
:param nc32: the number of feature maps in the first stage (where feature maps are 32x32)
:param nc16: the number of feature maps in the second stage (where feature maps are 16x16)
:param nc8: the number of feature maps in the third stage (where feature maps are 8x8)
"""
super(ResNet, self).__init__()
# Parameters of the model
padding = 1
stride = 1
kernel_size = 3
eps = 2e-5
bias = False
# Initialization parameters
wscale = sqrt(2.) # This makes the initialization equal to that of He et al.
# The first layer is always a convolution.
self.c1 = nn.Conv2d(in_channels=3, out_channels=nc32, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 32x32 feature maps
layers_nc32 = []
for i in range(num_blocks):
layers_nc32.append(ResBlock2D(in_channels=nc32, out_channels=nc32, kernel_size=kernel_size, fiber_map='id', stride=stride, padding=padding))
self.layers_nc32 = nn.Sequential(*layers_nc32)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 16x16 feature maps
# The first convolution uses stride 2
layers_nc16 = []
for i in range(num_blocks):
stride_block = 1 if i > 0 else 2
fiber_map = 'id' if i > 0 else 'linear'
nc_in = nc16 if i > 0 else nc32
layers_nc16.append(ResBlock2D(in_channels=nc_in, out_channels=nc16, kernel_size=kernel_size, fiber_map=fiber_map, stride=stride_block, padding=padding))
self.layers_nc16 = nn.Sequential(*layers_nc16)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 8x8 feature maps
# The first convolution uses stride 2
layers_nc8 = []
for i in range(num_blocks):
stride_block = 1 if i > 0 else 2
fiber_map = 'id' if i > 0 else 'linear'
nc_in = nc8 if i > 0 else nc16
layers_nc8.append(ResBlock2D(in_channels=nc_in, out_channels=nc8, kernel_size=kernel_size, fiber_map=fiber_map, stride=stride_block, padding=padding))
self.layers_nc8 = nn.Sequential(*layers_nc8)
# Add BN and final layer
# We do ReLU and average pooling between BN and final layer,
# but since these are stateless they don't require a Link.
self.bn_out = nn.BatchNorm2d(num_features=nc8, eps=eps)
self.c_out = nn.Conv2d(in_channels=nc8, out_channels=10, kernel_size=1, stride=1, padding=0, bias=bias)
# Initialization:
for m in self.modules():
if isinstance(m, nn.Conv2d):
m.weight.data.normal_(0, wscale * torch.prod(torch.Tensor(list(m.weight.shape)[1:]))**(-1/2))
def forward(self, x):
h = x
# First conv layer
h = self.c1(h)
# Residual blocks
h = self.layers_nc32(h)
h = self.layers_nc16(h)
h = self.layers_nc8(h)
# BN, relu, pool, final layer
h = self.bn_out(h)
h = torch.relu(h)
h = torch.nn.functional.avg_pool2d(h, kernel_size=h.shape[-1])
h = self.c_out(h)
h = h.view(h.size(0), 10)
return h
# New style residual block
class ResBlock2D(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, fiber_map='id', stride=1, padding=1):
super(ResBlock2D, self).__init__()
# Asserts
assert kernel_size % 2 == 1
if not padding == (kernel_size - 1) // 2:
raise NotImplementedError()
# Parameters of the model
eps = 2e-5
bias = False
if stride != 1:
self.really_equivariant = True
self.pooling = torch.max_pool2d
else:
self.really_equivariant = False
self.bn1 = nn.BatchNorm2d(num_features=in_channels, eps=eps)
self.c1 = nn.Conv2d(in_channels=in_channels , out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias)
if self.really_equivariant:
self.c1 = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=1, padding=padding, bias=bias)
self.bn2 = nn.BatchNorm2d(num_features=out_channels, eps=eps)
self.c2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=kernel_size, stride=1 , padding=padding, bias=bias)
if fiber_map == 'id':
if not in_channels == out_channels:
raise ValueError('fiber_map cannot be identity when channel dimension is changed.')
self.fiber_map = nn.Sequential() # Identity
elif fiber_map == 'zero_pad':
raise NotImplementedError()
elif fiber_map == 'linear':
self.fiber_map = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride, padding=0, bias=bias)
if self.really_equivariant:
self.fiber_map = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0, bias=bias)
else:
raise ValueError('Unknown fiber_map: ' + str(type))
def forward(self, x):
h = self.c1(torch.relu(self.bn1(x)))
if self.really_equivariant:
h = self.pooling(h, kernel_size=2, stride=2, padding=0)
h = self.c2(torch.relu(self.bn2(h)))
hx = self.fiber_map(x)
if self.really_equivariant:
hx = self.pooling(hx, kernel_size=2, stride=2, padding=0)
return hx + h
# Based on implementation from Cohen & Welling (2016)
class P4MResNet(nn.Module):
def __init__(self, num_blocks=7, nc32=11, nc16=23, nc8=45):
"""
:param num_blocks: the number of resnet blocks per stage. There are 3 stages, for feature map width 32, 16, 8.
Total number of layers is 6 * num_blocks + 2
:param nc32: the number of feature maps in the first stage (where feature maps are 32x32)
:param nc16: the number of feature maps in the second stage (where feature maps are 16x16)
:param nc8: the number of feature maps in the third stage (where feature maps are 8x8)
"""
super(P4MResNet, self).__init__()
#Parameters of the group
# Import the group structure
import importlib
group_name = 'E2'
group = importlib.import_module('attgconv.group.' + group_name)
# Import the gsplintes package and the layers
import attgconv
e2_layers = attgconv.layers(group) # The layers is instantiated with the group structure as input
# Create H grid for p4 group
self.h_grid = e2_layers.H.grid_global(8) # 2*p4
# Parameters of the model
stride = 1
padding = 1
kernel_size = 3
eps = 2e-5
# Initialization parameters
wscale = sqrt(2.) # This makes the initialization equal to that of He et al.
# Pooling layer
self.avg_pooling = e2_layers.average_pooling_Rn
# The first layer is always a convolution.
self.c1 = e2_layers.ConvRnG(N_in=3, N_out=nc32, kernel_size=kernel_size, h_grid=self.h_grid, stride=stride, padding=padding, wscale=wscale)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 32x32 feature maps
layers_nc32 = []
for i in range(num_blocks):
layers_nc32.append(P4MResBlock2D(in_channels=nc32, out_channels=nc32, kernel_size=kernel_size, fiber_map='id', stride=stride, padding=padding, wscale=wscale))
self.layers_nc32 = nn.Sequential(*layers_nc32)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 16x16 feature maps
# The first convolution uses stride 2
layers_nc16 = []
for i in range(num_blocks):
stride_block = 1 if i > 0 else 2
fiber_map = 'id' if i > 0 else 'linear'
nc_in = nc16 if i > 0 else nc32
layers_nc16.append(P4MResBlock2D(in_channels=nc_in, out_channels=nc16, kernel_size=kernel_size, fiber_map=fiber_map, stride=stride_block, padding=padding, wscale=wscale))
self.layers_nc16 = nn.Sequential(*layers_nc16)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 8x8 feature maps
# The first convolution uses stride 2
layers_nc8 = []
for i in range(num_blocks):
stride_block = 1 if i > 0 else 2
fiber_map = 'id' if i > 0 else 'linear'
nc_in = nc8 if i > 0 else nc16
layers_nc8.append(P4MResBlock2D(in_channels=nc_in, out_channels=nc8, kernel_size=kernel_size, fiber_map=fiber_map, stride=stride_block, padding=padding, wscale=wscale))
self.layers_nc8 = nn.Sequential(*layers_nc8)
# Add BN and final layer
# We do ReLU and average pooling between BN and final layer,
# but since these are stateless they don't require a Link.
self.bn_out = nn.BatchNorm3d(num_features=nc8, eps=eps)
self.c_out = e2_layers.ConvGG(N_in=nc8, N_out=10, kernel_size=1, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=1, padding=0, wscale=wscale)
def forward(self, x):
#x = torch.flip(x, dims=[-2])
#x = torch.rot90(x, k=1, dims=[-2, -1])
h = x
# First conv layer
h = self.c1(h)
# Residual blocks
h = self.layers_nc32(h)
h = self.layers_nc16(h)
h = self.layers_nc8(h)
# BN, relu, pool, final layer
h = self.bn_out(h)
h = torch.relu(h)
h = self.avg_pooling(h, kernel_size=h.shape[-1], stride=1, padding=0) # TODO check!
h = self.c_out(h)
h = h.mean(dim=2)
h = h.view(h.size(0), 10)
return h
# New style residual block
class P4MResBlock2D(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, fiber_map='id', stride=1, padding=1, wscale=1.0):
super(P4MResBlock2D, self).__init__()
# Asserts
assert kernel_size % 2 == 1
if not padding == (kernel_size - 1) // 2:
raise NotImplementedError()
# Parameters of the group
# Import the group structure
import importlib
group_name = 'E2'
group = importlib.import_module('attgconv.group.' + group_name)
# Import the gsplintes package and the layers
import attgconv
e2_layers = attgconv.layers(group) # The layers is instantiated with the group structure as input
# Create H grid for p4 group
self.h_grid = e2_layers.H.grid_global(8) # 2*p4
# Parameters of the model
eps = 2e-5
if stride != 1:
self.really_equivariant = True
self.pooling = e2_layers.max_pooling_Rn
else:
self.really_equivariant = False
self.bn1 = nn.BatchNorm3d(num_features=in_channels, eps=eps)
self.c1 = e2_layers.ConvGG(N_in=in_channels , N_out=out_channels, kernel_size=kernel_size, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=stride, padding=padding, wscale=wscale)
if self.really_equivariant:
self.c1 = e2_layers.ConvGG(N_in=in_channels, N_out=out_channels, kernel_size=kernel_size, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=1, padding=padding, wscale=wscale)
self.bn2 = nn.BatchNorm3d(num_features=out_channels, eps=eps)
self.c2 = e2_layers.ConvGG(N_in=out_channels, N_out=out_channels, kernel_size=kernel_size, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=1 , padding=padding, wscale=wscale)
if fiber_map == 'id':
if not in_channels == out_channels:
raise ValueError('fiber_map cannot be identity when channel dimension is changed.')
self.fiber_map = nn.Sequential() # Identity
elif fiber_map == 'zero_pad':
raise NotImplementedError()
elif fiber_map == 'linear':
self.fiber_map = e2_layers.ConvGG(N_in=in_channels, N_out=out_channels, kernel_size=1, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=stride, padding=0, wscale=wscale)
if self.really_equivariant:
self.fiber_map = e2_layers.ConvGG(N_in=in_channels, N_out=out_channels, kernel_size=1, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=1, padding=0, wscale=wscale)
else:
raise ValueError('Unknown fiber_map: ' + str(type))
def forward(self, x):
h = self.c1(torch.relu(self.bn1(x)))
if self.really_equivariant:
h = self.pooling(h, kernel_size=2, stride=2, padding=0)
h = self.c2(torch.relu(self.bn2(h)))
hx = self.fiber_map(x)
if self.really_equivariant:
hx = self.pooling(hx, kernel_size=2, stride=2, padding=0)
return hx + h
# Based on implementation from <NAME> (2016)
class fA_P4MResNet(nn.Module):
def __init__(self, num_blocks=7, nc32=11, nc16=23, nc8=45):
"""
:param num_blocks: the number of resnet blocks per stage. There are 3 stages, for feature map width 32, 16, 8.
Total number of layers is 6 * num_blocks + 2
:param nc32: the number of feature maps in the first stage (where feature maps are 32x32)
:param nc16: the number of feature maps in the second stage (where feature maps are 16x16)
:param nc8: the number of feature maps in the third stage (where feature maps are 8x8)
"""
super(fA_P4MResNet, self).__init__()
#Parameters of the group
# Import the group structure
import importlib
group_name = 'E2'
group = importlib.import_module('attgconv.group.' + group_name)
# Import the gsplintes package and the layers
import attgconv
e2_layers = attgconv.layers(group) # The layers is instantiated with the group structure as input
# Create H grid for p4m group
n_grid = 8
h_grid = e2_layers.H.grid_global(n_grid)
# ----------------------
# Parameters of the model
stride = 1
padding = 1
kernel_size = 3
eps = 2e-5
# --------------------------------------------------------
# Store in self
self.group_name = group_name
self.group = group
self.layers = e2_layers
self.n_grid = n_grid
self.h_grid = h_grid
# ----------------------
# Initialization parameters
wscale = sqrt(2.) # This makes the initialization equal to that of He et al.
# ----------------------
# Parameters of attention
ch_ratio = 16
sp_kernel_size = 7
sp_padding = (sp_kernel_size // 2)
from attgconv.attention_layers import fChannelAttention as ch_RnG
from attgconv.attention_layers import fChannelAttentionGG # as ch_GG
from attgconv.attention_layers import fSpatialAttention # as sp_RnG
from attgconv.attention_layers import fSpatialAttentionGG
ch_GG = functools.partial(fChannelAttentionGG, N_h_in=n_grid, group=group_name)
sp_RnG = functools.partial(fSpatialAttention, wscale=wscale)
sp_GG = functools.partial(fSpatialAttentionGG, group=group, input_h_grid=self.h_grid, wscale=wscale)
# Pooling layer
self.avg_pooling = e2_layers.average_pooling_Rn
# The first layer is always a convolution.
self.c1 = e2_layers.fAttConvRnG(N_in=3, N_out=nc32, kernel_size=kernel_size, h_grid=self.h_grid, stride=stride, padding=padding, wscale=wscale,
channel_attention=ch_RnG(N_in=3, ratio=1),
spatial_attention=sp_RnG(group=group, kernel_size=sp_kernel_size, h_grid=self.h_grid)
)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 32x32 feature maps
layers_nc32 = []
for i in range(num_blocks):
layers_nc32.append(fA_P4MResBlock2D(in_channels=nc32, out_channels=nc32, kernel_size=kernel_size, fiber_map='id', stride=stride, padding=padding, wscale=wscale))
self.layers_nc32 = nn.Sequential(*layers_nc32)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 16x16 feature maps
# The first convolution uses stride 2
layers_nc16 = []
for i in range(num_blocks):
stride_block = 1 if i > 0 else 2
fiber_map = 'id' if i > 0 else 'linear'
nc_in = nc16 if i > 0 else nc32
layers_nc16.append(fA_P4MResBlock2D(in_channels=nc_in, out_channels=nc16, kernel_size=kernel_size, fiber_map=fiber_map, stride=stride_block, padding=padding, wscale=wscale))
self.layers_nc16 = nn.Sequential(*layers_nc16)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 8x8 feature maps
# The first convolution uses stride 2
layers_nc8 = []
for i in range(num_blocks):
stride_block = 1 if i > 0 else 2
fiber_map = 'id' if i > 0 else 'linear'
nc_in = nc8 if i > 0 else nc16
layers_nc8.append(fA_P4MResBlock2D(in_channels=nc_in, out_channels=nc8, kernel_size=kernel_size, fiber_map=fiber_map, stride=stride_block, padding=padding, wscale=wscale))
self.layers_nc8 = nn.Sequential(*layers_nc8)
# Add BN and final layer
# We do ReLU and average pooling between BN and final layer,
# but since these are stateless they don't require a Link.
self.bn_out = nn.BatchNorm3d(num_features=nc8, eps=eps)
self.c_out = e2_layers.fAttConvGG(N_in=nc8, N_out=10, kernel_size=1, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=1, padding=0, wscale=wscale,
channel_attention=ch_GG(N_in=nc8, ratio=nc8 // 2),
spatial_attention=sp_GG(kernel_size=sp_kernel_size)
)
def forward(self, x):
x = torch.flip(x, dims=[-1])
h = x
# First conv layer
h = self.c1(h)
# Residual blocks
h = self.layers_nc32(h)
h = self.layers_nc16(h)
h = self.layers_nc8(h)
# BN, relu, pool, final layer
h = self.bn_out(h)
h = torch.relu(h)
h = self.avg_pooling(h, kernel_size=h.shape[-1], stride=1, padding=0) # TODO check!
h = self.c_out(h)
h = h.mean(dim=2)
h = h.view(h.size(0), 10)
return h
# New style residual block
class fA_P4MResBlock2D(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, fiber_map='id', stride=1, padding=1, wscale=1.0):
super(fA_P4MResBlock2D, self).__init__()
# Asserts
assert kernel_size % 2 == 1
if not padding == (kernel_size - 1) // 2:
raise NotImplementedError()
# Parameters of the group
# Import the group structure
import importlib
group_name = 'E2'
group = importlib.import_module('attgconv.group.' + group_name)
# Import the gsplintes package and the layers
import attgconv
e2_layers = attgconv.layers(group) # The layers is instantiated with the group structure as input
# Create H grid for p4 group
n_grid = 8
self.h_grid = e2_layers.H.grid_global(n_grid) # 2*p4
# ----------------------
# Parameters of the model
eps = 2e-5
# ----------------------
# Parameters of attention
#ch_ratio = 16
sp_kernel_size = 7
sp_padding = (sp_kernel_size // 2)
# --------------------------------------------------------
from attgconv.attention_layers import fChannelAttention as ch_RnG
from attgconv.attention_layers import fChannelAttentionGG # as ch_GG
from attgconv.attention_layers import fSpatialAttention # as sp_RnG
from attgconv.attention_layers import fSpatialAttentionGG
ch_GG = functools.partial(fChannelAttentionGG, N_h_in=n_grid, group=group_name)
sp_RnG = functools.partial(fSpatialAttention, wscale=wscale)
sp_GG = functools.partial(fSpatialAttentionGG, group=group, input_h_grid=self.h_grid, wscale=wscale)
if stride != 1:
self.really_equivariant = True
self.pooling = e2_layers.max_pooling_Rn
else:
self.really_equivariant = False
self.bn1 = nn.BatchNorm3d(num_features=in_channels, eps=eps)
self.c1 = e2_layers.fAttConvGG(N_in=in_channels , N_out=out_channels, kernel_size=kernel_size, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=stride, padding=padding, wscale=wscale,
channel_attention=ch_GG(N_in=in_channels, ratio=in_channels // 2),
spatial_attention=sp_GG(kernel_size=sp_kernel_size)
)
if self.really_equivariant:
self.c1 = e2_layers.fAttConvGG(N_in=in_channels, N_out=out_channels, kernel_size=kernel_size, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=1, padding=padding, wscale=wscale,
channel_attention=ch_GG(N_in=in_channels, ratio=in_channels // 2),
spatial_attention=sp_GG(kernel_size=sp_kernel_size)
)
self.bn2 = nn.BatchNorm3d(num_features=out_channels, eps=eps)
self.c2 = e2_layers.fAttConvGG(N_in=out_channels, N_out=out_channels, kernel_size=kernel_size, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=1 , padding=padding, wscale=wscale,
channel_attention=ch_GG(N_in=out_channels, ratio=out_channels // 2),
spatial_attention=sp_GG(kernel_size=sp_kernel_size)
)
if fiber_map == 'id':
if not in_channels == out_channels:
raise ValueError('fiber_map cannot be identity when channel dimension is changed.')
self.fiber_map = nn.Sequential() # Identity
elif fiber_map == 'zero_pad':
raise NotImplementedError()
elif fiber_map == 'linear':
self.fiber_map = e2_layers.fAttConvGG(N_in=in_channels, N_out=out_channels, kernel_size=1, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=stride, padding=0, wscale=wscale,
channel_attention=ch_GG(N_in=in_channels, ratio=in_channels // 2),
spatial_attention=sp_GG(kernel_size=sp_kernel_size)
)
if self.really_equivariant:
self.fiber_map = e2_layers.fAttConvGG(N_in=in_channels, N_out=out_channels, kernel_size=1, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=1, padding=0, wscale=wscale,
channel_attention=ch_GG(N_in=in_channels, ratio=in_channels // 2),
spatial_attention=sp_GG(kernel_size=sp_kernel_size)
)
else:
raise ValueError('Unknown fiber_map: ' + str(type))
def forward(self, x):
h = self.c1(torch.relu(self.bn1(x)))
if self.really_equivariant:
h = self.pooling(h, kernel_size=2, stride=2, padding=0)
h = self.c2(torch.relu(self.bn2(h)))
hx = self.fiber_map(x)
if self.really_equivariant:
hx = self.pooling(hx, kernel_size=2, stride=2, padding=0)
return hx + h
if __name__ == '__main__':
from experiments.utils import num_params
model = ResNet()
model(torch.rand([1, 3, 32, 32])) # Sanity check
num_params(model)
model = P4MResNet()
model(torch.rand([1, 3, 32, 32])) # Sanity check
num_params(model)
model = fA_P4MResNet()
model(torch.rand([1, 3, 32, 32])) # Sanity check
num_params(model) | experiments/cifar10/models/resnet.py | import torch
import torch.nn as nn
# built-in
from math import sqrt
import functools
# Based on implementation from <NAME> (2016)
class ResNet(nn.Module):
def __init__(self, num_blocks=7, nc32=32, nc16=64, nc8=128):
"""
:param num_blocks: the number of resnet blocks per stage. There are 3 stages, for feature map width 32, 16, 8.
Total number of layers is 6 * num_blocks + 2
:param nc32: the number of feature maps in the first stage (where feature maps are 32x32)
:param nc16: the number of feature maps in the second stage (where feature maps are 16x16)
:param nc8: the number of feature maps in the third stage (where feature maps are 8x8)
"""
super(ResNet, self).__init__()
# Parameters of the model
padding = 1
stride = 1
kernel_size = 3
eps = 2e-5
bias = False
# Initialization parameters
wscale = sqrt(2.) # This makes the initialization equal to that of He et al.
# The first layer is always a convolution.
self.c1 = nn.Conv2d(in_channels=3, out_channels=nc32, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 32x32 feature maps
layers_nc32 = []
for i in range(num_blocks):
layers_nc32.append(ResBlock2D(in_channels=nc32, out_channels=nc32, kernel_size=kernel_size, fiber_map='id', stride=stride, padding=padding))
self.layers_nc32 = nn.Sequential(*layers_nc32)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 16x16 feature maps
# The first convolution uses stride 2
layers_nc16 = []
for i in range(num_blocks):
stride_block = 1 if i > 0 else 2
fiber_map = 'id' if i > 0 else 'linear'
nc_in = nc16 if i > 0 else nc32
layers_nc16.append(ResBlock2D(in_channels=nc_in, out_channels=nc16, kernel_size=kernel_size, fiber_map=fiber_map, stride=stride_block, padding=padding))
self.layers_nc16 = nn.Sequential(*layers_nc16)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 8x8 feature maps
# The first convolution uses stride 2
layers_nc8 = []
for i in range(num_blocks):
stride_block = 1 if i > 0 else 2
fiber_map = 'id' if i > 0 else 'linear'
nc_in = nc8 if i > 0 else nc16
layers_nc8.append(ResBlock2D(in_channels=nc_in, out_channels=nc8, kernel_size=kernel_size, fiber_map=fiber_map, stride=stride_block, padding=padding))
self.layers_nc8 = nn.Sequential(*layers_nc8)
# Add BN and final layer
# We do ReLU and average pooling between BN and final layer,
# but since these are stateless they don't require a Link.
self.bn_out = nn.BatchNorm2d(num_features=nc8, eps=eps)
self.c_out = nn.Conv2d(in_channels=nc8, out_channels=10, kernel_size=1, stride=1, padding=0, bias=bias)
# Initialization:
for m in self.modules():
if isinstance(m, nn.Conv2d):
m.weight.data.normal_(0, wscale * torch.prod(torch.Tensor(list(m.weight.shape)[1:]))**(-1/2))
def forward(self, x):
h = x
# First conv layer
h = self.c1(h)
# Residual blocks
h = self.layers_nc32(h)
h = self.layers_nc16(h)
h = self.layers_nc8(h)
# BN, relu, pool, final layer
h = self.bn_out(h)
h = torch.relu(h)
h = torch.nn.functional.avg_pool2d(h, kernel_size=h.shape[-1])
h = self.c_out(h)
h = h.view(h.size(0), 10)
return h
# New style residual block
class ResBlock2D(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, fiber_map='id', stride=1, padding=1):
super(ResBlock2D, self).__init__()
# Asserts
assert kernel_size % 2 == 1
if not padding == (kernel_size - 1) // 2:
raise NotImplementedError()
# Parameters of the model
eps = 2e-5
bias = False
if stride != 1:
self.really_equivariant = True
self.pooling = torch.max_pool2d
else:
self.really_equivariant = False
self.bn1 = nn.BatchNorm2d(num_features=in_channels, eps=eps)
self.c1 = nn.Conv2d(in_channels=in_channels , out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias)
if self.really_equivariant:
self.c1 = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=1, padding=padding, bias=bias)
self.bn2 = nn.BatchNorm2d(num_features=out_channels, eps=eps)
self.c2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=kernel_size, stride=1 , padding=padding, bias=bias)
if fiber_map == 'id':
if not in_channels == out_channels:
raise ValueError('fiber_map cannot be identity when channel dimension is changed.')
self.fiber_map = nn.Sequential() # Identity
elif fiber_map == 'zero_pad':
raise NotImplementedError()
elif fiber_map == 'linear':
self.fiber_map = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride, padding=0, bias=bias)
if self.really_equivariant:
self.fiber_map = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0, bias=bias)
else:
raise ValueError('Unknown fiber_map: ' + str(type))
def forward(self, x):
h = self.c1(torch.relu(self.bn1(x)))
if self.really_equivariant:
h = self.pooling(h, kernel_size=2, stride=2, padding=0)
h = self.c2(torch.relu(self.bn2(h)))
hx = self.fiber_map(x)
if self.really_equivariant:
hx = self.pooling(hx, kernel_size=2, stride=2, padding=0)
return hx + h
# Based on implementation from Cohen & Welling (2016)
class P4MResNet(nn.Module):
def __init__(self, num_blocks=7, nc32=11, nc16=23, nc8=45):
"""
:param num_blocks: the number of resnet blocks per stage. There are 3 stages, for feature map width 32, 16, 8.
Total number of layers is 6 * num_blocks + 2
:param nc32: the number of feature maps in the first stage (where feature maps are 32x32)
:param nc16: the number of feature maps in the second stage (where feature maps are 16x16)
:param nc8: the number of feature maps in the third stage (where feature maps are 8x8)
"""
super(P4MResNet, self).__init__()
#Parameters of the group
# Import the group structure
import importlib
group_name = 'E2'
group = importlib.import_module('attgconv.group.' + group_name)
# Import the gsplintes package and the layers
import attgconv
e2_layers = attgconv.layers(group) # The layers is instantiated with the group structure as input
# Create H grid for p4 group
self.h_grid = e2_layers.H.grid_global(8) # 2*p4
# Parameters of the model
stride = 1
padding = 1
kernel_size = 3
eps = 2e-5
# Initialization parameters
wscale = sqrt(2.) # This makes the initialization equal to that of He et al.
# Pooling layer
self.avg_pooling = e2_layers.average_pooling_Rn
# The first layer is always a convolution.
self.c1 = e2_layers.ConvRnG(N_in=3, N_out=nc32, kernel_size=kernel_size, h_grid=self.h_grid, stride=stride, padding=padding, wscale=wscale)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 32x32 feature maps
layers_nc32 = []
for i in range(num_blocks):
layers_nc32.append(P4MResBlock2D(in_channels=nc32, out_channels=nc32, kernel_size=kernel_size, fiber_map='id', stride=stride, padding=padding, wscale=wscale))
self.layers_nc32 = nn.Sequential(*layers_nc32)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 16x16 feature maps
# The first convolution uses stride 2
layers_nc16 = []
for i in range(num_blocks):
stride_block = 1 if i > 0 else 2
fiber_map = 'id' if i > 0 else 'linear'
nc_in = nc16 if i > 0 else nc32
layers_nc16.append(P4MResBlock2D(in_channels=nc_in, out_channels=nc16, kernel_size=kernel_size, fiber_map=fiber_map, stride=stride_block, padding=padding, wscale=wscale))
self.layers_nc16 = nn.Sequential(*layers_nc16)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 8x8 feature maps
# The first convolution uses stride 2
layers_nc8 = []
for i in range(num_blocks):
stride_block = 1 if i > 0 else 2
fiber_map = 'id' if i > 0 else 'linear'
nc_in = nc8 if i > 0 else nc16
layers_nc8.append(P4MResBlock2D(in_channels=nc_in, out_channels=nc8, kernel_size=kernel_size, fiber_map=fiber_map, stride=stride_block, padding=padding, wscale=wscale))
self.layers_nc8 = nn.Sequential(*layers_nc8)
# Add BN and final layer
# We do ReLU and average pooling between BN and final layer,
# but since these are stateless they don't require a Link.
self.bn_out = nn.BatchNorm3d(num_features=nc8, eps=eps)
self.c_out = e2_layers.ConvGG(N_in=nc8, N_out=10, kernel_size=1, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=1, padding=0, wscale=wscale)
def forward(self, x):
#x = torch.flip(x, dims=[-2])
#x = torch.rot90(x, k=1, dims=[-2, -1])
h = x
# First conv layer
h = self.c1(h)
# Residual blocks
h = self.layers_nc32(h)
h = self.layers_nc16(h)
h = self.layers_nc8(h)
# BN, relu, pool, final layer
h = self.bn_out(h)
h = torch.relu(h)
h = self.avg_pooling(h, kernel_size=h.shape[-1], stride=1, padding=0) # TODO check!
h = self.c_out(h)
h = h.mean(dim=2)
h = h.view(h.size(0), 10)
return h
# New style residual block
class P4MResBlock2D(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, fiber_map='id', stride=1, padding=1, wscale=1.0):
super(P4MResBlock2D, self).__init__()
# Asserts
assert kernel_size % 2 == 1
if not padding == (kernel_size - 1) // 2:
raise NotImplementedError()
# Parameters of the group
# Import the group structure
import importlib
group_name = 'E2'
group = importlib.import_module('attgconv.group.' + group_name)
# Import the gsplintes package and the layers
import attgconv
e2_layers = attgconv.layers(group) # The layers is instantiated with the group structure as input
# Create H grid for p4 group
self.h_grid = e2_layers.H.grid_global(8) # 2*p4
# Parameters of the model
eps = 2e-5
if stride != 1:
self.really_equivariant = True
self.pooling = e2_layers.max_pooling_Rn
else:
self.really_equivariant = False
self.bn1 = nn.BatchNorm3d(num_features=in_channels, eps=eps)
self.c1 = e2_layers.ConvGG(N_in=in_channels , N_out=out_channels, kernel_size=kernel_size, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=stride, padding=padding, wscale=wscale)
if self.really_equivariant:
self.c1 = e2_layers.ConvGG(N_in=in_channels, N_out=out_channels, kernel_size=kernel_size, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=1, padding=padding, wscale=wscale)
self.bn2 = nn.BatchNorm3d(num_features=out_channels, eps=eps)
self.c2 = e2_layers.ConvGG(N_in=out_channels, N_out=out_channels, kernel_size=kernel_size, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=1 , padding=padding, wscale=wscale)
if fiber_map == 'id':
if not in_channels == out_channels:
raise ValueError('fiber_map cannot be identity when channel dimension is changed.')
self.fiber_map = nn.Sequential() # Identity
elif fiber_map == 'zero_pad':
raise NotImplementedError()
elif fiber_map == 'linear':
self.fiber_map = e2_layers.ConvGG(N_in=in_channels, N_out=out_channels, kernel_size=1, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=stride, padding=0, wscale=wscale)
if self.really_equivariant:
self.fiber_map = e2_layers.ConvGG(N_in=in_channels, N_out=out_channels, kernel_size=1, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=1, padding=0, wscale=wscale)
else:
raise ValueError('Unknown fiber_map: ' + str(type))
def forward(self, x):
h = self.c1(torch.relu(self.bn1(x)))
if self.really_equivariant:
h = self.pooling(h, kernel_size=2, stride=2, padding=0)
h = self.c2(torch.relu(self.bn2(h)))
hx = self.fiber_map(x)
if self.really_equivariant:
hx = self.pooling(hx, kernel_size=2, stride=2, padding=0)
return hx + h
# Based on implementation from <NAME> (2016)
class fA_P4MResNet(nn.Module):
def __init__(self, num_blocks=7, nc32=11, nc16=23, nc8=45):
"""
:param num_blocks: the number of resnet blocks per stage. There are 3 stages, for feature map width 32, 16, 8.
Total number of layers is 6 * num_blocks + 2
:param nc32: the number of feature maps in the first stage (where feature maps are 32x32)
:param nc16: the number of feature maps in the second stage (where feature maps are 16x16)
:param nc8: the number of feature maps in the third stage (where feature maps are 8x8)
"""
super(fA_P4MResNet, self).__init__()
#Parameters of the group
# Import the group structure
import importlib
group_name = 'E2'
group = importlib.import_module('attgconv.group.' + group_name)
# Import the gsplintes package and the layers
import attgconv
e2_layers = attgconv.layers(group) # The layers is instantiated with the group structure as input
# Create H grid for p4m group
n_grid = 8
h_grid = e2_layers.H.grid_global(n_grid)
# ----------------------
# Parameters of the model
stride = 1
padding = 1
kernel_size = 3
eps = 2e-5
# --------------------------------------------------------
# Store in self
self.group_name = group_name
self.group = group
self.layers = e2_layers
self.n_grid = n_grid
self.h_grid = h_grid
# ----------------------
# Initialization parameters
wscale = sqrt(2.) # This makes the initialization equal to that of He et al.
# ----------------------
# Parameters of attention
ch_ratio = 16
sp_kernel_size = 7
sp_padding = (sp_kernel_size // 2)
from attgconv.attention_layers import fChannelAttention as ch_RnG
from attgconv.attention_layers import fChannelAttentionGG # as ch_GG
from attgconv.attention_layers import fSpatialAttention # as sp_RnG
from attgconv.attention_layers import fSpatialAttentionGG
ch_GG = functools.partial(fChannelAttentionGG, N_h_in=n_grid, group=group_name)
sp_RnG = functools.partial(fSpatialAttention, wscale=wscale)
sp_GG = functools.partial(fSpatialAttentionGG, group=group, input_h_grid=self.h_grid, wscale=wscale)
# Pooling layer
self.avg_pooling = e2_layers.average_pooling_Rn
# The first layer is always a convolution.
self.c1 = e2_layers.fAttConvRnG(N_in=3, N_out=nc32, kernel_size=kernel_size, h_grid=self.h_grid, stride=stride, padding=padding, wscale=wscale,
channel_attention=ch_RnG(N_in=3, ratio=1),
spatial_attention=sp_RnG(group=group, kernel_size=sp_kernel_size, h_grid=self.h_grid)
)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 32x32 feature maps
layers_nc32 = []
for i in range(num_blocks):
layers_nc32.append(fA_P4MResBlock2D(in_channels=nc32, out_channels=nc32, kernel_size=kernel_size, fiber_map='id', stride=stride, padding=padding, wscale=wscale))
self.layers_nc32 = nn.Sequential(*layers_nc32)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 16x16 feature maps
# The first convolution uses stride 2
layers_nc16 = []
for i in range(num_blocks):
stride_block = 1 if i > 0 else 2
fiber_map = 'id' if i > 0 else 'linear'
nc_in = nc16 if i > 0 else nc32
layers_nc16.append(fA_P4MResBlock2D(in_channels=nc_in, out_channels=nc16, kernel_size=kernel_size, fiber_map=fiber_map, stride=stride_block, padding=padding, wscale=wscale))
self.layers_nc16 = nn.Sequential(*layers_nc16)
# Add num_blocks ResBlocks (2 * num_blocks layers) for the size 8x8 feature maps
# The first convolution uses stride 2
layers_nc8 = []
for i in range(num_blocks):
stride_block = 1 if i > 0 else 2
fiber_map = 'id' if i > 0 else 'linear'
nc_in = nc8 if i > 0 else nc16
layers_nc8.append(fA_P4MResBlock2D(in_channels=nc_in, out_channels=nc8, kernel_size=kernel_size, fiber_map=fiber_map, stride=stride_block, padding=padding, wscale=wscale))
self.layers_nc8 = nn.Sequential(*layers_nc8)
# Add BN and final layer
# We do ReLU and average pooling between BN and final layer,
# but since these are stateless they don't require a Link.
self.bn_out = nn.BatchNorm3d(num_features=nc8, eps=eps)
self.c_out = e2_layers.fAttConvGG(N_in=nc8, N_out=10, kernel_size=1, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=1, padding=0, wscale=wscale,
channel_attention=ch_GG(N_in=nc8, ratio=nc8 // 2),
spatial_attention=sp_GG(kernel_size=sp_kernel_size)
)
def forward(self, x):
x = torch.flip(x, dims=[-1])
h = x
# First conv layer
h = self.c1(h)
# Residual blocks
h = self.layers_nc32(h)
h = self.layers_nc16(h)
h = self.layers_nc8(h)
# BN, relu, pool, final layer
h = self.bn_out(h)
h = torch.relu(h)
h = self.avg_pooling(h, kernel_size=h.shape[-1], stride=1, padding=0) # TODO check!
h = self.c_out(h)
h = h.mean(dim=2)
h = h.view(h.size(0), 10)
return h
# New style residual block
class fA_P4MResBlock2D(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, fiber_map='id', stride=1, padding=1, wscale=1.0):
super(fA_P4MResBlock2D, self).__init__()
# Asserts
assert kernel_size % 2 == 1
if not padding == (kernel_size - 1) // 2:
raise NotImplementedError()
# Parameters of the group
# Import the group structure
import importlib
group_name = 'E2'
group = importlib.import_module('attgconv.group.' + group_name)
# Import the gsplintes package and the layers
import attgconv
e2_layers = attgconv.layers(group) # The layers is instantiated with the group structure as input
# Create H grid for p4 group
n_grid = 8
self.h_grid = e2_layers.H.grid_global(n_grid) # 2*p4
# ----------------------
# Parameters of the model
eps = 2e-5
# ----------------------
# Parameters of attention
#ch_ratio = 16
sp_kernel_size = 7
sp_padding = (sp_kernel_size // 2)
# --------------------------------------------------------
from attgconv.attention_layers import fChannelAttention as ch_RnG
from attgconv.attention_layers import fChannelAttentionGG # as ch_GG
from attgconv.attention_layers import fSpatialAttention # as sp_RnG
from attgconv.attention_layers import fSpatialAttentionGG
ch_GG = functools.partial(fChannelAttentionGG, N_h_in=n_grid, group=group_name)
sp_RnG = functools.partial(fSpatialAttention, wscale=wscale)
sp_GG = functools.partial(fSpatialAttentionGG, group=group, input_h_grid=self.h_grid, wscale=wscale)
if stride != 1:
self.really_equivariant = True
self.pooling = e2_layers.max_pooling_Rn
else:
self.really_equivariant = False
self.bn1 = nn.BatchNorm3d(num_features=in_channels, eps=eps)
self.c1 = e2_layers.fAttConvGG(N_in=in_channels , N_out=out_channels, kernel_size=kernel_size, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=stride, padding=padding, wscale=wscale,
channel_attention=ch_GG(N_in=in_channels, ratio=in_channels // 2),
spatial_attention=sp_GG(kernel_size=sp_kernel_size)
)
if self.really_equivariant:
self.c1 = e2_layers.fAttConvGG(N_in=in_channels, N_out=out_channels, kernel_size=kernel_size, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=1, padding=padding, wscale=wscale,
channel_attention=ch_GG(N_in=in_channels, ratio=in_channels // 2),
spatial_attention=sp_GG(kernel_size=sp_kernel_size)
)
self.bn2 = nn.BatchNorm3d(num_features=out_channels, eps=eps)
self.c2 = e2_layers.fAttConvGG(N_in=out_channels, N_out=out_channels, kernel_size=kernel_size, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=1 , padding=padding, wscale=wscale,
channel_attention=ch_GG(N_in=out_channels, ratio=out_channels // 2),
spatial_attention=sp_GG(kernel_size=sp_kernel_size)
)
if fiber_map == 'id':
if not in_channels == out_channels:
raise ValueError('fiber_map cannot be identity when channel dimension is changed.')
self.fiber_map = nn.Sequential() # Identity
elif fiber_map == 'zero_pad':
raise NotImplementedError()
elif fiber_map == 'linear':
self.fiber_map = e2_layers.fAttConvGG(N_in=in_channels, N_out=out_channels, kernel_size=1, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=stride, padding=0, wscale=wscale,
channel_attention=ch_GG(N_in=in_channels, ratio=in_channels // 2),
spatial_attention=sp_GG(kernel_size=sp_kernel_size)
)
if self.really_equivariant:
self.fiber_map = e2_layers.fAttConvGG(N_in=in_channels, N_out=out_channels, kernel_size=1, h_grid=self.h_grid, input_h_grid=self.h_grid, stride=1, padding=0, wscale=wscale,
channel_attention=ch_GG(N_in=in_channels, ratio=in_channels // 2),
spatial_attention=sp_GG(kernel_size=sp_kernel_size)
)
else:
raise ValueError('Unknown fiber_map: ' + str(type))
def forward(self, x):
h = self.c1(torch.relu(self.bn1(x)))
if self.really_equivariant:
h = self.pooling(h, kernel_size=2, stride=2, padding=0)
h = self.c2(torch.relu(self.bn2(h)))
hx = self.fiber_map(x)
if self.really_equivariant:
hx = self.pooling(hx, kernel_size=2, stride=2, padding=0)
return hx + h
if __name__ == '__main__':
from experiments.utils import num_params
model = ResNet()
model(torch.rand([1, 3, 32, 32])) # Sanity check
num_params(model)
model = P4MResNet()
model(torch.rand([1, 3, 32, 32])) # Sanity check
num_params(model)
model = fA_P4MResNet()
model(torch.rand([1, 3, 32, 32])) # Sanity check
num_params(model) | 0.955142 | 0.494385 |
import re
from typing import List, Optional
from parso.python.tree import Module
from globality_black.constants import (
MAX_CHARACTERS_TO_FIND_INDENTATION_PARENT,
TYPES_TO_CHECK_FMT_ON_OFF,
)
class SyntaxTreeVisitor:
def __init__(
self,
module: Module,
types_to_find: Optional[List[str]] = None,
):
self.module = module
self.types_to_find = types_to_find
self.fmt_off = False
def __call__(self, node):
self.set_fmt_on_off_according_to_prefix(node)
if self.types_to_find is None or node.type in self.types_to_find and not self.fmt_off:
yield node
if hasattr(node, "children"):
for child in node.children:
self.set_fmt_on_off_according_to_prefix(child)
if not self.fmt_off:
yield from self(child)
def set_fmt_on_off_according_to_prefix(self, node):
"""
We check for fmt_on_off only for some specific types, otherwise no-op. This saves time, so
we don't need to find the prefix for every single node in the parse tree
"""
if not any(name in node.type for name in TYPES_TO_CHECK_FMT_ON_OFF):
return
prefix = node.get_first_leaf().prefix
if "fmt: off" in prefix:
self.fmt_off = True
if "fmt: on" in prefix:
self.fmt_off = False
def apply_function_to_tree_prefixes(module, root, function):
visitor = SyntaxTreeVisitor(module)
for node in visitor(root):
prefix = node.get_first_leaf().prefix
node.get_first_leaf().prefix = function(prefix)
def find_indentation_parent_prefix(element):
"""
Find prefix for the indentation parent by going to the parent's line and getting the indent
for the first element in the line, i.e. the node we have to align this element with
Examples:
x = foo(arg1="marc",) --> indentation parent for arg1 is x (his grand-grand-parent)
foo(arg1="marc",) --> indentation parent for arg1 is foo (his grand-parent)
"""
parent = element.parent
module = element.get_root_node()
line_start_pos = (parent.start_pos[0], 0)
leaf = module.get_leaf_for_position(line_start_pos, include_prefixes=True)
# we move the "pointer" to position 0 of this line and check if the leaf.type is not a newline
# otherwise we keep moving the pointer until we find something, and that gives as the
# indentation sized we're looking for
while leaf.type == "newline":
leaf = module.get_leaf_for_position(line_start_pos, include_prefixes=True)
line_start_pos = (line_start_pos[0], line_start_pos[1] + 1)
if line_start_pos[1] > MAX_CHARACTERS_TO_FIND_INDENTATION_PARENT:
raise ValueError(
"Warning: no leaf found in this line after "
f"{MAX_CHARACTERS_TO_FIND_INDENTATION_PARENT} characters. "
f"Looking for parent for leaf:\n{leaf.get_code()}"
)
return leaf.prefix
def get_indent_from_prefix(prefix):
"""
Each element in parso has a prefix. We want to get the indent from the parent, so we can
construct the prefix for the modified elements.
Example:
def foo(
arg1="marc", arg2=" at ", arg3="globality",
):
return arg1 + arg2 + arg3
arg1 has prefix "\n ". Here we get the " ".
"""
if prefix:
try:
return re.search("( *)$", prefix).group(0)
except Exception:
raise ValueError(f"Could not get indent from prefix {prefix}")
else:
return prefix | globality_black/common.py | import re
from typing import List, Optional
from parso.python.tree import Module
from globality_black.constants import (
MAX_CHARACTERS_TO_FIND_INDENTATION_PARENT,
TYPES_TO_CHECK_FMT_ON_OFF,
)
class SyntaxTreeVisitor:
def __init__(
self,
module: Module,
types_to_find: Optional[List[str]] = None,
):
self.module = module
self.types_to_find = types_to_find
self.fmt_off = False
def __call__(self, node):
self.set_fmt_on_off_according_to_prefix(node)
if self.types_to_find is None or node.type in self.types_to_find and not self.fmt_off:
yield node
if hasattr(node, "children"):
for child in node.children:
self.set_fmt_on_off_according_to_prefix(child)
if not self.fmt_off:
yield from self(child)
def set_fmt_on_off_according_to_prefix(self, node):
"""
We check for fmt_on_off only for some specific types, otherwise no-op. This saves time, so
we don't need to find the prefix for every single node in the parse tree
"""
if not any(name in node.type for name in TYPES_TO_CHECK_FMT_ON_OFF):
return
prefix = node.get_first_leaf().prefix
if "fmt: off" in prefix:
self.fmt_off = True
if "fmt: on" in prefix:
self.fmt_off = False
def apply_function_to_tree_prefixes(module, root, function):
visitor = SyntaxTreeVisitor(module)
for node in visitor(root):
prefix = node.get_first_leaf().prefix
node.get_first_leaf().prefix = function(prefix)
def find_indentation_parent_prefix(element):
"""
Find prefix for the indentation parent by going to the parent's line and getting the indent
for the first element in the line, i.e. the node we have to align this element with
Examples:
x = foo(arg1="marc",) --> indentation parent for arg1 is x (his grand-grand-parent)
foo(arg1="marc",) --> indentation parent for arg1 is foo (his grand-parent)
"""
parent = element.parent
module = element.get_root_node()
line_start_pos = (parent.start_pos[0], 0)
leaf = module.get_leaf_for_position(line_start_pos, include_prefixes=True)
# we move the "pointer" to position 0 of this line and check if the leaf.type is not a newline
# otherwise we keep moving the pointer until we find something, and that gives as the
# indentation sized we're looking for
while leaf.type == "newline":
leaf = module.get_leaf_for_position(line_start_pos, include_prefixes=True)
line_start_pos = (line_start_pos[0], line_start_pos[1] + 1)
if line_start_pos[1] > MAX_CHARACTERS_TO_FIND_INDENTATION_PARENT:
raise ValueError(
"Warning: no leaf found in this line after "
f"{MAX_CHARACTERS_TO_FIND_INDENTATION_PARENT} characters. "
f"Looking for parent for leaf:\n{leaf.get_code()}"
)
return leaf.prefix
def get_indent_from_prefix(prefix):
"""
Each element in parso has a prefix. We want to get the indent from the parent, so we can
construct the prefix for the modified elements.
Example:
def foo(
arg1="marc", arg2=" at ", arg3="globality",
):
return arg1 + arg2 + arg3
arg1 has prefix "\n ". Here we get the " ".
"""
if prefix:
try:
return re.search("( *)$", prefix).group(0)
except Exception:
raise ValueError(f"Could not get indent from prefix {prefix}")
else:
return prefix | 0.783077 | 0.323754 |
import httplib
import json
import logging
from conpaas.core import https
class AgentException(Exception):
pass
def _check(response):
code, body = response
if code != httplib.OK:
raise AgentException('Received HTTP response code %d' % (code))
try:
data = json.loads(body)
except Exception as e:
raise AgentException(*e.args)
if data['error']:
raise AgentException(data['error'])
elif data['result']:
return data['result']
else:
return True
def start_mysqld(host, port, nodes=None, device_name=None):
method = 'start_mysqld'
nodes = nodes or []
params = {'nodes': nodes,
'device_name': device_name}
return _check(https.client.jsonrpc_post(host, port, '/', method, params=params))
def configure_user(host, port, username, password):
method = 'configure_user'
params = {'username': username,
'password': password}
return _check(https.client.jsonrpc_post(host, port, '/', method, params=params))
def get_all_users(host, port):
method = 'get_all_users'
result = https.client.jsonrpc_get(host, port, '/', method)
if _check(result):
return result
else:
return False
def set_password(host, port, username, password):
method = 'set_password'
params = {'username': username,
'password': password}
return _check(https.client.jsonrpc_post(host, port, '/', method, params=params))
def remove_user(host, port, name):
method = 'remove_user'
params = {'username': name}
return _check(https.client.jsonrpc_get(host, port, '/', method, params=params))
def check_agent_process(host, port):
method = 'check_agent_process'
return _check(https.client.jsonrpc_get(host, port, '/', method))
def load_dump(host, port, mysqldump_path):
params = {'method': 'load_dump'}
f = open(mysqldump_path, 'r')
filecontent = f.read()
f.close()
files = [('mysqldump_file', mysqldump_path, filecontent)]
return _check(https.client.https_post(host, port, '/', params=params, files=files))
def stop(host, port):
method = 'stop'
return _check(https.client.jsonrpc_post(host, port, '/', method))
def getLoad(host, port):
method = 'getLoad'
return _check(https.client.jsonrpc_get(host, port, '/', method))
def start_glbd(host, port, nodes):
method = 'start_glbd'
params = {'nodes': nodes}
return _check(https.client.jsonrpc_post(host, port, '/', method, params=params))
def add_glbd_nodes(host, port, nodesIp):
method = 'add_glbd_nodes'
params = {'nodesIp': nodesIp}
return _check(https.client.jsonrpc_post(host, port, '/', method, params=params))
def remove_glbd_nodes(host, port, nodes):
method = 'remove_glbd_nodes'
params = {'nodes': nodes}
return _check(https.client.jsonrpc_post(host, port, '/', method, params=params)) | conpaas-services/src/conpaas/services/mysql/agent/client.py | import httplib
import json
import logging
from conpaas.core import https
class AgentException(Exception):
pass
def _check(response):
code, body = response
if code != httplib.OK:
raise AgentException('Received HTTP response code %d' % (code))
try:
data = json.loads(body)
except Exception as e:
raise AgentException(*e.args)
if data['error']:
raise AgentException(data['error'])
elif data['result']:
return data['result']
else:
return True
def start_mysqld(host, port, nodes=None, device_name=None):
method = 'start_mysqld'
nodes = nodes or []
params = {'nodes': nodes,
'device_name': device_name}
return _check(https.client.jsonrpc_post(host, port, '/', method, params=params))
def configure_user(host, port, username, password):
method = 'configure_user'
params = {'username': username,
'password': password}
return _check(https.client.jsonrpc_post(host, port, '/', method, params=params))
def get_all_users(host, port):
method = 'get_all_users'
result = https.client.jsonrpc_get(host, port, '/', method)
if _check(result):
return result
else:
return False
def set_password(host, port, username, password):
method = 'set_password'
params = {'username': username,
'password': password}
return _check(https.client.jsonrpc_post(host, port, '/', method, params=params))
def remove_user(host, port, name):
method = 'remove_user'
params = {'username': name}
return _check(https.client.jsonrpc_get(host, port, '/', method, params=params))
def check_agent_process(host, port):
method = 'check_agent_process'
return _check(https.client.jsonrpc_get(host, port, '/', method))
def load_dump(host, port, mysqldump_path):
params = {'method': 'load_dump'}
f = open(mysqldump_path, 'r')
filecontent = f.read()
f.close()
files = [('mysqldump_file', mysqldump_path, filecontent)]
return _check(https.client.https_post(host, port, '/', params=params, files=files))
def stop(host, port):
method = 'stop'
return _check(https.client.jsonrpc_post(host, port, '/', method))
def getLoad(host, port):
method = 'getLoad'
return _check(https.client.jsonrpc_get(host, port, '/', method))
def start_glbd(host, port, nodes):
method = 'start_glbd'
params = {'nodes': nodes}
return _check(https.client.jsonrpc_post(host, port, '/', method, params=params))
def add_glbd_nodes(host, port, nodesIp):
method = 'add_glbd_nodes'
params = {'nodesIp': nodesIp}
return _check(https.client.jsonrpc_post(host, port, '/', method, params=params))
def remove_glbd_nodes(host, port, nodes):
method = 'remove_glbd_nodes'
params = {'nodes': nodes}
return _check(https.client.jsonrpc_post(host, port, '/', method, params=params)) | 0.202286 | 0.095898 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import tensorflow as tf
class SearchableKernelMaker:
def make_searchable_kernel_w_and_conds(self, kernel_w, tf_masks, thresholds, is_supergraph_training_tensor,
can_zeroout, equal_selection=True):
"""
Makes searchable_kernel.
Kernel will be chosen among the followings
k_0 : kernel_w * tf_masks[0]
k_1 : kernel_w * (tf_masks[0] + tf_masks[1]),
k_2 : kernel_w * (tf_masks[0] + tf_masks[1] + tf_masks[2]), ...
if norm(kernel_w * tf_masks[i]) > thresholds[i] for all i < n, use k_n.
thresholds[0] will choose whether or not to use k_0, k_1, k_2, ...
thresholds[1] will choose whether or not to use k_1, k_2, ...
:param kernel_w: kernel weight to make into searchable form
:param tf_masks: tensorflow tensor masks which indicate the form of searchable kernel.
All the elements should be 0 or 1,
And when summed up, they have to be identical with np.ones(kernel_w.shape)
:param thresholds: List of tensors with shape [1]. Can be trainable if one wants to change this by training.
Must be the same length with tf_masks.
:param is_supergraph_training_tensor: tensor with shape [1], which indicate the supergraph is training.
:param can_zeroout: if True, this kernel_w will be able to be zeroed out totally.
It thinks that this will make this layer to be skip-op
"""
# FIXME: this is awkward... these two variables have to be combined, but how?
splitted_kernels = [kernel_w * mask for mask in tf_masks]
self.norms_per_splitted_kernels = [tf.norm(splitted_kernel) for splitted_kernel in splitted_kernels]
useconds_of_splitted_kernel = self.__diffble_islargerthanT(self.norms_per_splitted_kernels, thresholds)
if is_supergraph_training_tensor is not None:
assert equal_selection
useconds_of_splitted_kernel = self.__add_equal_drop_per_split(useconds_of_splitted_kernel,
is_supergraph_training_tensor)
if not can_zeroout:
self.__avoid_zerooutall_cond(useconds_of_splitted_kernel)
return combine_to_nested_form(splitted_kernels, useconds_of_splitted_kernel), useconds_of_splitted_kernel
def _get_norms_per_kernels(self):
"""
For debugging purpose. Make sure to call this after you made searchable_kernel
"""
return self.norms_per_splitted_kernels
@classmethod
def __diffble_islargerthanT(cls, values, thresholds):
assert len(values) == len(thresholds)
useconds_of_splitted_kernel = [diffible_indicator(v - t) for v, t in zip(values, thresholds)]
return useconds_of_splitted_kernel
@classmethod
def __add_equal_drop_per_split(cls, useconds_of_splitted_kernel, is_supergraph_training):
"""
This equation was calculated when is_supergraph_training is 1 or 0.
We will have total split_nums + 1 selections. Let's call this n + 1
So, to make equal drops, each selection point, i.e. each useconds have to be dropped by
1/(n+1), 1/n, 1/(n-1), ... 1/2.
Then, all selections can be selected by prob
1/(n+1), 1/n * n/(n+1), 1/(n-1) * (n-1)/n * n/(n+1), ...
This equation works even when the first condition is fixed by 1, by __avoid_zerooutall_cond.
Because, remaining selections will be selected by prob 1/n.
"""
dropped_useconds = []
split_nums = len(useconds_of_splitted_kernel)
for i in range(split_nums):
drop_prob = is_supergraph_training * 1 / (split_nums + 1 - i)
dropped_useconds.append(add_dropout(useconds_of_splitted_kernel[i], drop_prob))
return dropped_useconds
@classmethod
def __avoid_zerooutall_cond(cls, useconds_of_splitted_kernel):
# Note that zeroout must be done only in the first threshold
useconds_of_splitted_kernel[0] = tf.ones([1])
def diffible_indicator(x):
return tf.stop_gradient(tf.to_float(x >= 0) - tf.sigmoid(x)) + tf.sigmoid(x)
def add_dropout(tensor, drop_prob):
return tf.nn.dropout(tensor, rate=drop_prob)
def combine_to_nested_form(splitted_kernels, useconds_of_splitted_kernel):
"""
For example, if splitted_kernels = [c50%, c100%], useconds = [use_ehalf, use_efull],
return use_ehalf * (c50% + use_efull * c100%)
:param splitted_kernels:
:param useconds_of_splitted_kernel:
:return:
"""
assert len(splitted_kernels) == len(useconds_of_splitted_kernel)
if len(splitted_kernels) == 1:
return useconds_of_splitted_kernel[0] * splitted_kernels[0]
else:
return useconds_of_splitted_kernel[0] * \
(splitted_kernels[0] + combine_to_nested_form(splitted_kernels[1:], useconds_of_splitted_kernel[1:]))
def calc_useconds_of_value_in_list(wanted, sel_list, useconds_of_selections, can_zeroout=False):
"""
If you used combine_to_searchable_form to construct the splitted_kernels,
You can calculate usecond value for wanted value in sel_list with this ftn
"""
if wanted == 0:
assert can_zeroout
return 1 - useconds_of_selections[0]
assert wanted in sel_list
assert len(sel_list) == len(useconds_of_selections)
result = tf.ones((1,))
for i, (selection, usecond) in enumerate(zip(sel_list, useconds_of_selections)):
result = result * usecond
if selection == wanted:
break
not_last_selection = (i + 1 < len(sel_list))
if not_last_selection:
result = result * (1 - useconds_of_selections[i + 1])
return result
def interpret_useconds(sel_list, useconds_of_selections):
"""
interprets value of useconds.
returns 0 if all the useconds are zero. i.e. that means skipop (expand_ratio=0)
"""
assert len(sel_list) == len(useconds_of_selections)
result = 0
for selection, usecond in zip(sel_list, useconds_of_selections):
if usecond == 0:
break
result = selection
return result
def test_interpret_useconds():
C_sel_list = [32, 64, 128]
assert 0 == interpret_useconds(C_sel_list, useconds_of_selections=[0, 0, 0])
assert 32 == interpret_useconds(C_sel_list, useconds_of_selections=[1, 0, 0])
assert 64 == interpret_useconds(C_sel_list, useconds_of_selections=[1, 1, 0])
assert 128 == interpret_useconds(C_sel_list, useconds_of_selections=[1, 1, 1])
assert 32 == interpret_useconds(C_sel_list, useconds_of_selections=[1, 0, 1])
assert 0 == interpret_useconds(C_sel_list, useconds_of_selections=[0, 1, 1])
print("passed test_interpret_useconds")
def test_useconds_of_value_in_list():
C_sel_list = [32, 64]
with tf.Session() as sess:
usecond_32, usecond_64 = tf.Variable((0.0)), tf.Variable((0.0))
sess.run(tf.global_variables_initializer())
usecond_for_ = {wanted: calc_useconds_of_value_in_list(wanted, C_sel_list, [usecond_32, usecond_64], can_zeroout=True)
for wanted in [0, 32, 64]}
def check_val(tensor, value):
tensor_val = sess.run(tensor).item()
assert tensor_val == value, "%f" % tensor_val
check_val(usecond_for_[0], 1)
check_val(usecond_for_[32], 0)
check_val(usecond_for_[64], 0)
sess.run(usecond_32.assign(1.0))
check_val(usecond_for_[0], 0)
check_val(usecond_for_[32], 1)
check_val(usecond_for_[64], 0)
sess.run(usecond_64.assign(1.0))
check_val(usecond_for_[0], 0)
check_val(usecond_for_[32], 0)
check_val(usecond_for_[64], 1)
sess.run(usecond_32.assign(0.0))
check_val(usecond_for_[0], 1)
check_val(usecond_for_[32], 0)
check_val(usecond_for_[64], 0)
print("passed useconds_of_value_in_list")
if __name__ == '__main__':
test_useconds_of_value_in_list()
test_interpret_useconds() | graph/searchable_utils.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import tensorflow as tf
class SearchableKernelMaker:
def make_searchable_kernel_w_and_conds(self, kernel_w, tf_masks, thresholds, is_supergraph_training_tensor,
can_zeroout, equal_selection=True):
"""
Makes searchable_kernel.
Kernel will be chosen among the followings
k_0 : kernel_w * tf_masks[0]
k_1 : kernel_w * (tf_masks[0] + tf_masks[1]),
k_2 : kernel_w * (tf_masks[0] + tf_masks[1] + tf_masks[2]), ...
if norm(kernel_w * tf_masks[i]) > thresholds[i] for all i < n, use k_n.
thresholds[0] will choose whether or not to use k_0, k_1, k_2, ...
thresholds[1] will choose whether or not to use k_1, k_2, ...
:param kernel_w: kernel weight to make into searchable form
:param tf_masks: tensorflow tensor masks which indicate the form of searchable kernel.
All the elements should be 0 or 1,
And when summed up, they have to be identical with np.ones(kernel_w.shape)
:param thresholds: List of tensors with shape [1]. Can be trainable if one wants to change this by training.
Must be the same length with tf_masks.
:param is_supergraph_training_tensor: tensor with shape [1], which indicate the supergraph is training.
:param can_zeroout: if True, this kernel_w will be able to be zeroed out totally.
It thinks that this will make this layer to be skip-op
"""
# FIXME: this is awkward... these two variables have to be combined, but how?
splitted_kernels = [kernel_w * mask for mask in tf_masks]
self.norms_per_splitted_kernels = [tf.norm(splitted_kernel) for splitted_kernel in splitted_kernels]
useconds_of_splitted_kernel = self.__diffble_islargerthanT(self.norms_per_splitted_kernels, thresholds)
if is_supergraph_training_tensor is not None:
assert equal_selection
useconds_of_splitted_kernel = self.__add_equal_drop_per_split(useconds_of_splitted_kernel,
is_supergraph_training_tensor)
if not can_zeroout:
self.__avoid_zerooutall_cond(useconds_of_splitted_kernel)
return combine_to_nested_form(splitted_kernels, useconds_of_splitted_kernel), useconds_of_splitted_kernel
def _get_norms_per_kernels(self):
"""
For debugging purpose. Make sure to call this after you made searchable_kernel
"""
return self.norms_per_splitted_kernels
@classmethod
def __diffble_islargerthanT(cls, values, thresholds):
assert len(values) == len(thresholds)
useconds_of_splitted_kernel = [diffible_indicator(v - t) for v, t in zip(values, thresholds)]
return useconds_of_splitted_kernel
@classmethod
def __add_equal_drop_per_split(cls, useconds_of_splitted_kernel, is_supergraph_training):
"""
This equation was calculated when is_supergraph_training is 1 or 0.
We will have total split_nums + 1 selections. Let's call this n + 1
So, to make equal drops, each selection point, i.e. each useconds have to be dropped by
1/(n+1), 1/n, 1/(n-1), ... 1/2.
Then, all selections can be selected by prob
1/(n+1), 1/n * n/(n+1), 1/(n-1) * (n-1)/n * n/(n+1), ...
This equation works even when the first condition is fixed by 1, by __avoid_zerooutall_cond.
Because, remaining selections will be selected by prob 1/n.
"""
dropped_useconds = []
split_nums = len(useconds_of_splitted_kernel)
for i in range(split_nums):
drop_prob = is_supergraph_training * 1 / (split_nums + 1 - i)
dropped_useconds.append(add_dropout(useconds_of_splitted_kernel[i], drop_prob))
return dropped_useconds
@classmethod
def __avoid_zerooutall_cond(cls, useconds_of_splitted_kernel):
# Note that zeroout must be done only in the first threshold
useconds_of_splitted_kernel[0] = tf.ones([1])
def diffible_indicator(x):
return tf.stop_gradient(tf.to_float(x >= 0) - tf.sigmoid(x)) + tf.sigmoid(x)
def add_dropout(tensor, drop_prob):
return tf.nn.dropout(tensor, rate=drop_prob)
def combine_to_nested_form(splitted_kernels, useconds_of_splitted_kernel):
"""
For example, if splitted_kernels = [c50%, c100%], useconds = [use_ehalf, use_efull],
return use_ehalf * (c50% + use_efull * c100%)
:param splitted_kernels:
:param useconds_of_splitted_kernel:
:return:
"""
assert len(splitted_kernels) == len(useconds_of_splitted_kernel)
if len(splitted_kernels) == 1:
return useconds_of_splitted_kernel[0] * splitted_kernels[0]
else:
return useconds_of_splitted_kernel[0] * \
(splitted_kernels[0] + combine_to_nested_form(splitted_kernels[1:], useconds_of_splitted_kernel[1:]))
def calc_useconds_of_value_in_list(wanted, sel_list, useconds_of_selections, can_zeroout=False):
"""
If you used combine_to_searchable_form to construct the splitted_kernels,
You can calculate usecond value for wanted value in sel_list with this ftn
"""
if wanted == 0:
assert can_zeroout
return 1 - useconds_of_selections[0]
assert wanted in sel_list
assert len(sel_list) == len(useconds_of_selections)
result = tf.ones((1,))
for i, (selection, usecond) in enumerate(zip(sel_list, useconds_of_selections)):
result = result * usecond
if selection == wanted:
break
not_last_selection = (i + 1 < len(sel_list))
if not_last_selection:
result = result * (1 - useconds_of_selections[i + 1])
return result
def interpret_useconds(sel_list, useconds_of_selections):
"""
interprets value of useconds.
returns 0 if all the useconds are zero. i.e. that means skipop (expand_ratio=0)
"""
assert len(sel_list) == len(useconds_of_selections)
result = 0
for selection, usecond in zip(sel_list, useconds_of_selections):
if usecond == 0:
break
result = selection
return result
def test_interpret_useconds():
C_sel_list = [32, 64, 128]
assert 0 == interpret_useconds(C_sel_list, useconds_of_selections=[0, 0, 0])
assert 32 == interpret_useconds(C_sel_list, useconds_of_selections=[1, 0, 0])
assert 64 == interpret_useconds(C_sel_list, useconds_of_selections=[1, 1, 0])
assert 128 == interpret_useconds(C_sel_list, useconds_of_selections=[1, 1, 1])
assert 32 == interpret_useconds(C_sel_list, useconds_of_selections=[1, 0, 1])
assert 0 == interpret_useconds(C_sel_list, useconds_of_selections=[0, 1, 1])
print("passed test_interpret_useconds")
def test_useconds_of_value_in_list():
C_sel_list = [32, 64]
with tf.Session() as sess:
usecond_32, usecond_64 = tf.Variable((0.0)), tf.Variable((0.0))
sess.run(tf.global_variables_initializer())
usecond_for_ = {wanted: calc_useconds_of_value_in_list(wanted, C_sel_list, [usecond_32, usecond_64], can_zeroout=True)
for wanted in [0, 32, 64]}
def check_val(tensor, value):
tensor_val = sess.run(tensor).item()
assert tensor_val == value, "%f" % tensor_val
check_val(usecond_for_[0], 1)
check_val(usecond_for_[32], 0)
check_val(usecond_for_[64], 0)
sess.run(usecond_32.assign(1.0))
check_val(usecond_for_[0], 0)
check_val(usecond_for_[32], 1)
check_val(usecond_for_[64], 0)
sess.run(usecond_64.assign(1.0))
check_val(usecond_for_[0], 0)
check_val(usecond_for_[32], 0)
check_val(usecond_for_[64], 1)
sess.run(usecond_32.assign(0.0))
check_val(usecond_for_[0], 1)
check_val(usecond_for_[32], 0)
check_val(usecond_for_[64], 0)
print("passed useconds_of_value_in_list")
if __name__ == '__main__':
test_useconds_of_value_in_list()
test_interpret_useconds() | 0.701917 | 0.525004 |
import os
import logging
import uuid
import threading
import webbrowser
import datetime
from typing import Any
from typing import List
from typing import Optional
from typing import Dict
import msal
import flask
import requests
from flask import request
from werkzeug.serving import make_server
app = flask.Flask(__name__)
state = str(uuid.uuid4())
cache = msal.SerializableTokenCache()
@app.route("/msal")
def endpoint_auth() -> Any:
if not request.args.get("state") == state:
return flask.jsonify({"state": "error", "message": "Invalid request state"})
if "error" in request.args:
return flask.jsonify({"state": "error", **request.args})
if request.args.get("code"):
result = MicrosoftGraph.from_env()._acquire_token(request.args["code"])
if "error" in result:
return flask.jsonify({"state": "error", "message": result})
_shutdown_after_request()
return flask.jsonify({"state": "success", "message": "ok"})
class MicrosoftGraphError(Exception):
pass
class Event:
date_fmt = "%Y-%m-%dT%H:%M:%S.%f"
def __init__(
self,
subject: str = "Working on some code",
description: Optional[str] = None,
start: Optional[datetime.datetime] = None,
end: Optional[datetime.datetime] = None,
with_reminder: bool = False,
) -> None:
self.subject = subject
self.description = description or ""
self.start = start or datetime.datetime.now(datetime.timezone.utc)
self.end = end or self.start + datetime.timedelta(minutes=15)
self.with_reminder = with_reminder
if self.start.tzinfo is None or self.end.tzinfo is None:
raise MicrosoftGraphError(
"Unable to create an event with timezone unaware dates: "
f"start: {self.start} end: {self.end} ({self.subject})"
)
def json(self) -> Dict[str, Any]:
rv = {
"subject": self.subject,
"isReminderOn": self.with_reminder,
"sensitivity": "personal",
"showAs": "busy",
"start": {
"dateTime": self.start.strftime(self.date_fmt),
"timeZone": self.start.tzname(),
},
"end": {
"dateTime": self.end.strftime(self.date_fmt),
"timeZone": self.end.tzname(),
},
}
if self.description:
rv["body"] = {"contentType": "HTML", "content": self.description}
return rv
class MicrosoftGraph:
__instance = None
def __init__(self, client_id: str, client_secret: str, authority: str) -> None:
self.client_id = client_id
self.client_secret = client_secret
self.authority = authority
self._client: msal.ClientApplication = None
self._cache = cache
self._port = 8231
self._host = "localhost"
self._redirect_url = f"http://{self._host}:{self._port}/msal"
self._scopes: List[str] = ["User.ReadBasic.All", "Calendars.ReadWrite"]
@classmethod
def from_env(cls) -> "MicrosoftGraph":
if not cls.__instance:
client_id = _osvar_or_err("MS_CLIENT_ID")
client_secret = _osvar_or_err("MS_CLIENT_SECRET")
authority = _osvar_or_err("MS_AUTHORITY")
cls.__instance = MicrosoftGraph(
client_id,
client_secret,
f"https://login.microsoftonline.com/{authority}",
)
return cls.__instance
@property
def client(self) -> msal.ClientApplication:
if not self._client:
self._client = msal.ConfidentialClientApplication(
self.client_id,
authority=self.authority,
client_credential=self.client_secret,
token_cache=self._cache,
)
return self._client
@property
def token(self) -> str:
accounts = self.client.get_accounts()
if not accounts:
return ""
token: Dict[str, str] = self.client.acquire_token_silent(
self._scopes, accounts[0]
)
return token["access_token"]
def _acquire_token(self, code: str) -> Dict[str, Any]:
token_data: Dict[str, Any] = self.client.acquire_token_by_authorization_code(
code, self._scopes, self._redirect_url
)
return token_data
def authenticate(self) -> None:
url = self.client.get_authorization_request_url(
self._scopes, state=state, redirect_uri=self._redirect_url
)
server = make_server(self._host, self._port, app)
app.app_context().push()
srv = threading.Thread(target=server.serve_forever)
srv.start()
logging.info(url)
webbrowser.open(url)
srv.join()
def schedule_meeting(self, event: Event) -> None:
url = "https://graph.microsoft.com/v1.0/me/events"
rv = requests.post(
url, json=event.json(), headers={"Authorization": f"Bearer {self.token}"}
)
logging.debug(str(rv.json()))
if rv.status_code not in (200, 201):
raise MicrosoftGraphError(rv.json())
def _shutdown_after_request() -> None:
q = request.environ.get("werkzeug.server.shutdown")
if q is None:
raise RuntimeError("Not running flask with Werkzeug!")
q()
def _osvar_or_err(var: str) -> str:
v = os.environ.get(var, None)
if not v:
raise MicrosoftGraphError(
f"Environment variable {var} is not set. "
"Please set it to an appropriate value and try again."
)
return v | flowd/integrations.py | import os
import logging
import uuid
import threading
import webbrowser
import datetime
from typing import Any
from typing import List
from typing import Optional
from typing import Dict
import msal
import flask
import requests
from flask import request
from werkzeug.serving import make_server
app = flask.Flask(__name__)
state = str(uuid.uuid4())
cache = msal.SerializableTokenCache()
@app.route("/msal")
def endpoint_auth() -> Any:
if not request.args.get("state") == state:
return flask.jsonify({"state": "error", "message": "Invalid request state"})
if "error" in request.args:
return flask.jsonify({"state": "error", **request.args})
if request.args.get("code"):
result = MicrosoftGraph.from_env()._acquire_token(request.args["code"])
if "error" in result:
return flask.jsonify({"state": "error", "message": result})
_shutdown_after_request()
return flask.jsonify({"state": "success", "message": "ok"})
class MicrosoftGraphError(Exception):
pass
class Event:
date_fmt = "%Y-%m-%dT%H:%M:%S.%f"
def __init__(
self,
subject: str = "Working on some code",
description: Optional[str] = None,
start: Optional[datetime.datetime] = None,
end: Optional[datetime.datetime] = None,
with_reminder: bool = False,
) -> None:
self.subject = subject
self.description = description or ""
self.start = start or datetime.datetime.now(datetime.timezone.utc)
self.end = end or self.start + datetime.timedelta(minutes=15)
self.with_reminder = with_reminder
if self.start.tzinfo is None or self.end.tzinfo is None:
raise MicrosoftGraphError(
"Unable to create an event with timezone unaware dates: "
f"start: {self.start} end: {self.end} ({self.subject})"
)
def json(self) -> Dict[str, Any]:
rv = {
"subject": self.subject,
"isReminderOn": self.with_reminder,
"sensitivity": "personal",
"showAs": "busy",
"start": {
"dateTime": self.start.strftime(self.date_fmt),
"timeZone": self.start.tzname(),
},
"end": {
"dateTime": self.end.strftime(self.date_fmt),
"timeZone": self.end.tzname(),
},
}
if self.description:
rv["body"] = {"contentType": "HTML", "content": self.description}
return rv
class MicrosoftGraph:
__instance = None
def __init__(self, client_id: str, client_secret: str, authority: str) -> None:
self.client_id = client_id
self.client_secret = client_secret
self.authority = authority
self._client: msal.ClientApplication = None
self._cache = cache
self._port = 8231
self._host = "localhost"
self._redirect_url = f"http://{self._host}:{self._port}/msal"
self._scopes: List[str] = ["User.ReadBasic.All", "Calendars.ReadWrite"]
@classmethod
def from_env(cls) -> "MicrosoftGraph":
if not cls.__instance:
client_id = _osvar_or_err("MS_CLIENT_ID")
client_secret = _osvar_or_err("MS_CLIENT_SECRET")
authority = _osvar_or_err("MS_AUTHORITY")
cls.__instance = MicrosoftGraph(
client_id,
client_secret,
f"https://login.microsoftonline.com/{authority}",
)
return cls.__instance
@property
def client(self) -> msal.ClientApplication:
if not self._client:
self._client = msal.ConfidentialClientApplication(
self.client_id,
authority=self.authority,
client_credential=self.client_secret,
token_cache=self._cache,
)
return self._client
@property
def token(self) -> str:
accounts = self.client.get_accounts()
if not accounts:
return ""
token: Dict[str, str] = self.client.acquire_token_silent(
self._scopes, accounts[0]
)
return token["access_token"]
def _acquire_token(self, code: str) -> Dict[str, Any]:
token_data: Dict[str, Any] = self.client.acquire_token_by_authorization_code(
code, self._scopes, self._redirect_url
)
return token_data
def authenticate(self) -> None:
url = self.client.get_authorization_request_url(
self._scopes, state=state, redirect_uri=self._redirect_url
)
server = make_server(self._host, self._port, app)
app.app_context().push()
srv = threading.Thread(target=server.serve_forever)
srv.start()
logging.info(url)
webbrowser.open(url)
srv.join()
def schedule_meeting(self, event: Event) -> None:
url = "https://graph.microsoft.com/v1.0/me/events"
rv = requests.post(
url, json=event.json(), headers={"Authorization": f"Bearer {self.token}"}
)
logging.debug(str(rv.json()))
if rv.status_code not in (200, 201):
raise MicrosoftGraphError(rv.json())
def _shutdown_after_request() -> None:
q = request.environ.get("werkzeug.server.shutdown")
if q is None:
raise RuntimeError("Not running flask with Werkzeug!")
q()
def _osvar_or_err(var: str) -> str:
v = os.environ.get(var, None)
if not v:
raise MicrosoftGraphError(
f"Environment variable {var} is not set. "
"Please set it to an appropriate value and try again."
)
return v | 0.756627 | 0.101145 |
import pandas as pd
import six
class InstrumentMixin(object):
def __init__(self, instruments):
self._instruments = {i.order_book_id: i for i in instruments}
self._sym_id_map = {i.symbol: k for k, i in six.iteritems(self._instruments)
# 过滤掉 CSI300, SSE50, CSI500, SSE180
if not i.order_book_id.endswith('INDX')}
# 沪深300 中证500 固定使用上证的
for o in ['000300.XSHG', '000905.XSHG']:
self._sym_id_map[self._instruments[o].symbol] = o
# 上证180 及 上证180指数 两个symbol都指向 000010.XSHG
self._sym_id_map[self._instruments['SSE180.INDX'].symbol] = '000010.XSHG'
def sector(self, code):
return [v.order_book_id for v in self._instruments.values()
if v.type == 'CS' and v.sector_code == code]
def industry(self, code):
return [v.order_book_id for v in self._instruments.values()
if v.type == 'CS' and v.industry_code == code]
def concept(self, *concepts):
return [v.order_book_id for v in self._instruments.values()
if v.type == 'CS' and any(c in v.concept_names.split('|') for c in concepts)]
def all_instruments(self, itype='CS'):
if itype is None:
return pd.DataFrame([[v.order_book_id, v.symbol, v.abbrev_symbol, v.type]
for v in self._instruments.values()],
columns=['order_book_id', 'symbol', 'abbrev_symbol', 'type'])
if itype not in ['CS', 'ETF', 'LOF', 'FenjiA', 'FenjiB', 'FenjiMu', 'INDX', 'Future']:
raise ValueError('Unknown type {}'.format(itype))
return pd.DataFrame([v.__dict__ for v in self._instruments.values() if v.type == itype])
def _instrument(self, sym_or_id):
try:
return self._instruments[sym_or_id]
except KeyError:
try:
sym_or_id = self._sym_id_map[sym_or_id]
return self._instruments[sym_or_id]
except KeyError:
return None
def instruments(self, sym_or_ids):
if isinstance(sym_or_ids, six.string_types):
return self._instrument(sym_or_ids)
return [i for i in [self._instrument(sid) for sid in sym_or_ids] if i is not None]
def get_future_contracts(self, underlying, date):
futures = [v for o, v in six.iteritems(self._instruments)
if v.type == 'Future' and v.underlying_symbol == underlying and
not o.endswith('88') and not o.endswith('99')]
if not futures:
return []
return sorted(i.order_book_id for i in futures if i.listed_date <= date <= i.de_listed_date) | rqalpha/data/instrument_mixin.py |
import pandas as pd
import six
class InstrumentMixin(object):
def __init__(self, instruments):
self._instruments = {i.order_book_id: i for i in instruments}
self._sym_id_map = {i.symbol: k for k, i in six.iteritems(self._instruments)
# 过滤掉 CSI300, SSE50, CSI500, SSE180
if not i.order_book_id.endswith('INDX')}
# 沪深300 中证500 固定使用上证的
for o in ['000300.XSHG', '000905.XSHG']:
self._sym_id_map[self._instruments[o].symbol] = o
# 上证180 及 上证180指数 两个symbol都指向 000010.XSHG
self._sym_id_map[self._instruments['SSE180.INDX'].symbol] = '000010.XSHG'
def sector(self, code):
return [v.order_book_id for v in self._instruments.values()
if v.type == 'CS' and v.sector_code == code]
def industry(self, code):
return [v.order_book_id for v in self._instruments.values()
if v.type == 'CS' and v.industry_code == code]
def concept(self, *concepts):
return [v.order_book_id for v in self._instruments.values()
if v.type == 'CS' and any(c in v.concept_names.split('|') for c in concepts)]
def all_instruments(self, itype='CS'):
if itype is None:
return pd.DataFrame([[v.order_book_id, v.symbol, v.abbrev_symbol, v.type]
for v in self._instruments.values()],
columns=['order_book_id', 'symbol', 'abbrev_symbol', 'type'])
if itype not in ['CS', 'ETF', 'LOF', 'FenjiA', 'FenjiB', 'FenjiMu', 'INDX', 'Future']:
raise ValueError('Unknown type {}'.format(itype))
return pd.DataFrame([v.__dict__ for v in self._instruments.values() if v.type == itype])
def _instrument(self, sym_or_id):
try:
return self._instruments[sym_or_id]
except KeyError:
try:
sym_or_id = self._sym_id_map[sym_or_id]
return self._instruments[sym_or_id]
except KeyError:
return None
def instruments(self, sym_or_ids):
if isinstance(sym_or_ids, six.string_types):
return self._instrument(sym_or_ids)
return [i for i in [self._instrument(sid) for sid in sym_or_ids] if i is not None]
def get_future_contracts(self, underlying, date):
futures = [v for o, v in six.iteritems(self._instruments)
if v.type == 'Future' and v.underlying_symbol == underlying and
not o.endswith('88') and not o.endswith('99')]
if not futures:
return []
return sorted(i.order_book_id for i in futures if i.listed_date <= date <= i.de_listed_date) | 0.36139 | 0.233717 |
from paida.paida_core.PAbsorber import *
from paida.paida_core.IBaseHistogram import *
from paida.paida_core.PExceptions import *
from paida.math.array.binArray import binArray3
class IHistogram(IBaseHistogram):
def __init__(self, title, binEdges):
IBaseHistogram.__init__(self, title)
self._sizeX = len(binEdges[0]) + 1
self._sizeY = len(binEdges[1]) + 1
self._sizeZ = len(binEdges[2]) + 1
self._reset()
def reset(self):
IBaseHistogram.reset(self)
self._reset()
def _reset(self):
sizeX = self._sizeX
sizeY = self._sizeY
sizeZ = self._sizeZ
self._binEntries = binArray3(sizeX, sizeY, sizeZ)
self._binSumOfWeights = binArray3(sizeX, sizeY, sizeZ)
self._binSumOfErrors = binArray3(sizeX, sizeY, sizeZ)
self._localReset()
def _innerIndex(self, innerX, innerY, innerZ):
return self._binEntries.getIndex(innerX, innerY, innerZ)
def allEntries(self):
return int(self._binEntries.sum())
def entries(self):
return int(self._binEntries.sumInRange())
def extraEntries(self):
return int(self._binEntries.sumOutRange())
def _sumWeights(self):
return self._binSumOfWeights.sum()
def _sumErrors(self):
return self._binSumOfErrors.sum()
def _sumInertialsX(self):
return self._binSumOfInertialsX.sum()
def _sumInertialsY(self):
return self._binSumOfInertialsY.sum()
def _sumInertialsZ(self):
return self._binSumOfInertialsZ.sum()
def _sumInertials(self):
return [self._sumInertialsX(), self._sumInertialsY(), self._sumInertialsZ()]
def _sumTorquesX(self):
return self._binSumOfTorquesX.sum()
def _sumTorquesY(self):
return self._binSumOfTorquesY.sum()
def _sumTorquesZ(self):
return self._binSumOfTorquesZ.sum()
def _sumTorques(self):
return [self._sumTorquesX(), self._sumTorquesY(), self._sumTorquesZ()]
def equivalentBinEntries(self):
try:
return self._sumWeights()**2 / self._sumErrors()
except ZeroDivisionError:
return 0.0
def sumAllBinHeights(self):
return self._binSumOfWeights.sum()
def sumBinHeights(self):
return self._binSumOfWeights.sumInRange()
def sumExtraBinHeights(self):
return self._binSumOfWeights.sumOutRange()
def minBinHeight(self):
if self._sizeY == 1:
rangeY = [0]
else:
rangeY = range(2, self._sizeY)
if self._sizeZ == 1:
rangeZ = [0]
else:
rangeZ = range(2, self._sizeZ)
binSumOfWeights = self._binSumOfWeights
result = binSumOfWeights[2, rangeY[0], rangeZ[0]]
for x in range(2, self._sizeX):
for y in rangeY:
for z in rangeZ:
result = min(result, binSumOfWeights[x, y, z])
return result
def maxBinHeight(self):
if self._sizeY == 1:
rangeY = [0]
else:
rangeY = range(2, self._sizeY)
if self._sizeZ == 1:
rangeZ = [0]
else:
rangeZ = range(2, self._sizeZ)
binSumOfWeights = self._binSumOfWeights
result = binSumOfWeights[2, rangeY[0], rangeZ[0]]
for x in range(2, self._sizeX):
for y in rangeY:
for z in rangeZ:
result = max(result, binSumOfWeights[x, y, z])
return result
def scale(self, factor):
if factor < 0:
raise IllegalArgumentException()
else:
factor = float(factor)
self._binSumOfWeights.scale(factor)
self._binSumOfErrors.scale(factor**2)
self._binSumOfTorquesX.scale(factor)
self._binSumOfTorquesY.scale(factor)
self._binSumOfTorquesZ.scale(factor)
self._binSumOfInertialsX.scale(factor)
self._binSumOfInertialsY.scale(factor)
self._binSumOfInertialsZ.scale(factor)
def _add(self, hist):
self._binEntries.add(hist._binEntries)
self._binSumOfWeights.add(hist._binSumOfWeights)
self._binSumOfErrors.add(hist._binSumOfErrors)
self._binSumOfTorquesX.add(hist._binSumOfTorquesX)
self._binSumOfTorquesY.add(hist._binSumOfTorquesY)
self._binSumOfTorquesZ.add(hist._binSumOfTorquesZ)
self._binSumOfInertialsX.add(hist._binSumOfInertialsX)
self._binSumOfInertialsY.add(hist._binSumOfInertialsY)
self._binSumOfInertialsZ.add(hist._binSumOfInertialsZ) | paida-3.2.1_2.10.1/paida/paida_core/IHistogram.py | from paida.paida_core.PAbsorber import *
from paida.paida_core.IBaseHistogram import *
from paida.paida_core.PExceptions import *
from paida.math.array.binArray import binArray3
class IHistogram(IBaseHistogram):
def __init__(self, title, binEdges):
IBaseHistogram.__init__(self, title)
self._sizeX = len(binEdges[0]) + 1
self._sizeY = len(binEdges[1]) + 1
self._sizeZ = len(binEdges[2]) + 1
self._reset()
def reset(self):
IBaseHistogram.reset(self)
self._reset()
def _reset(self):
sizeX = self._sizeX
sizeY = self._sizeY
sizeZ = self._sizeZ
self._binEntries = binArray3(sizeX, sizeY, sizeZ)
self._binSumOfWeights = binArray3(sizeX, sizeY, sizeZ)
self._binSumOfErrors = binArray3(sizeX, sizeY, sizeZ)
self._localReset()
def _innerIndex(self, innerX, innerY, innerZ):
return self._binEntries.getIndex(innerX, innerY, innerZ)
def allEntries(self):
return int(self._binEntries.sum())
def entries(self):
return int(self._binEntries.sumInRange())
def extraEntries(self):
return int(self._binEntries.sumOutRange())
def _sumWeights(self):
return self._binSumOfWeights.sum()
def _sumErrors(self):
return self._binSumOfErrors.sum()
def _sumInertialsX(self):
return self._binSumOfInertialsX.sum()
def _sumInertialsY(self):
return self._binSumOfInertialsY.sum()
def _sumInertialsZ(self):
return self._binSumOfInertialsZ.sum()
def _sumInertials(self):
return [self._sumInertialsX(), self._sumInertialsY(), self._sumInertialsZ()]
def _sumTorquesX(self):
return self._binSumOfTorquesX.sum()
def _sumTorquesY(self):
return self._binSumOfTorquesY.sum()
def _sumTorquesZ(self):
return self._binSumOfTorquesZ.sum()
def _sumTorques(self):
return [self._sumTorquesX(), self._sumTorquesY(), self._sumTorquesZ()]
def equivalentBinEntries(self):
try:
return self._sumWeights()**2 / self._sumErrors()
except ZeroDivisionError:
return 0.0
def sumAllBinHeights(self):
return self._binSumOfWeights.sum()
def sumBinHeights(self):
return self._binSumOfWeights.sumInRange()
def sumExtraBinHeights(self):
return self._binSumOfWeights.sumOutRange()
def minBinHeight(self):
if self._sizeY == 1:
rangeY = [0]
else:
rangeY = range(2, self._sizeY)
if self._sizeZ == 1:
rangeZ = [0]
else:
rangeZ = range(2, self._sizeZ)
binSumOfWeights = self._binSumOfWeights
result = binSumOfWeights[2, rangeY[0], rangeZ[0]]
for x in range(2, self._sizeX):
for y in rangeY:
for z in rangeZ:
result = min(result, binSumOfWeights[x, y, z])
return result
def maxBinHeight(self):
if self._sizeY == 1:
rangeY = [0]
else:
rangeY = range(2, self._sizeY)
if self._sizeZ == 1:
rangeZ = [0]
else:
rangeZ = range(2, self._sizeZ)
binSumOfWeights = self._binSumOfWeights
result = binSumOfWeights[2, rangeY[0], rangeZ[0]]
for x in range(2, self._sizeX):
for y in rangeY:
for z in rangeZ:
result = max(result, binSumOfWeights[x, y, z])
return result
def scale(self, factor):
if factor < 0:
raise IllegalArgumentException()
else:
factor = float(factor)
self._binSumOfWeights.scale(factor)
self._binSumOfErrors.scale(factor**2)
self._binSumOfTorquesX.scale(factor)
self._binSumOfTorquesY.scale(factor)
self._binSumOfTorquesZ.scale(factor)
self._binSumOfInertialsX.scale(factor)
self._binSumOfInertialsY.scale(factor)
self._binSumOfInertialsZ.scale(factor)
def _add(self, hist):
self._binEntries.add(hist._binEntries)
self._binSumOfWeights.add(hist._binSumOfWeights)
self._binSumOfErrors.add(hist._binSumOfErrors)
self._binSumOfTorquesX.add(hist._binSumOfTorquesX)
self._binSumOfTorquesY.add(hist._binSumOfTorquesY)
self._binSumOfTorquesZ.add(hist._binSumOfTorquesZ)
self._binSumOfInertialsX.add(hist._binSumOfInertialsX)
self._binSumOfInertialsY.add(hist._binSumOfInertialsY)
self._binSumOfInertialsZ.add(hist._binSumOfInertialsZ) | 0.490968 | 0.489015 |
import dash_html_components as html
import dash_bootstrap_components as dbc
import yaml
from navbar import Navbar
from footer import Footer
def Users():
"""Builds the AboutUs->Model Users using assets/users/organizations.yml"""
with open("assets/users/organizations.yml") as f:
collaborators = yaml.load(f, Loader=yaml.FullLoader)
collaborators = list(sorted(collaborators, key=lambda i: i["name"]))
def get_card(collab):
return dbc.Col(
style={"marginBottom": "32px"},
xs=12, sm=6, md=4, xl=4,
children=dbc.Card(
style={"borderColor": "#800020"},
className="h-100 collab-card",
children=[
dbc.CardHeader(html.H4(collab["name"]), style={"textAlign": "center"}),
dbc.CardImg(
src='assets/users/photos/%s' % collab['photo'],
top=False,
style={
"paddingLeft": "20px",
"paddingRight": "20px",
"paddingBottom": collab["padding"],
"paddingTop": collab["padding"],
}
),
dbc.CardFooter(
className="h-100",
children=[
html.A(
collab["text"],
href=collab["website"],
className="stretched-link collab-name"
),
],
),
dbc.CardFooter(
children=[
html.P("Model Used: " + collab["modelUsed"], style={"opacity": "0.6", "fontSize": 18})
]
)
],
),
)
body = dbc.Container(
className="page-body",
children=[
dbc.Row(
style={'marginBottom': 20},
children=[
dbc.Col([
html.H2("Model Users"),
html.P('Listed here are organizations who use our models to aid their decision making process.')
])
],
),
dbc.Row([
get_card(collaborators[i]) for i in range(len(collaborators))
]),
],
)
return html.Div([Navbar(), body, Footer()], className="site") | about_us/users.py | import dash_html_components as html
import dash_bootstrap_components as dbc
import yaml
from navbar import Navbar
from footer import Footer
def Users():
"""Builds the AboutUs->Model Users using assets/users/organizations.yml"""
with open("assets/users/organizations.yml") as f:
collaborators = yaml.load(f, Loader=yaml.FullLoader)
collaborators = list(sorted(collaborators, key=lambda i: i["name"]))
def get_card(collab):
return dbc.Col(
style={"marginBottom": "32px"},
xs=12, sm=6, md=4, xl=4,
children=dbc.Card(
style={"borderColor": "#800020"},
className="h-100 collab-card",
children=[
dbc.CardHeader(html.H4(collab["name"]), style={"textAlign": "center"}),
dbc.CardImg(
src='assets/users/photos/%s' % collab['photo'],
top=False,
style={
"paddingLeft": "20px",
"paddingRight": "20px",
"paddingBottom": collab["padding"],
"paddingTop": collab["padding"],
}
),
dbc.CardFooter(
className="h-100",
children=[
html.A(
collab["text"],
href=collab["website"],
className="stretched-link collab-name"
),
],
),
dbc.CardFooter(
children=[
html.P("Model Used: " + collab["modelUsed"], style={"opacity": "0.6", "fontSize": 18})
]
)
],
),
)
body = dbc.Container(
className="page-body",
children=[
dbc.Row(
style={'marginBottom': 20},
children=[
dbc.Col([
html.H2("Model Users"),
html.P('Listed here are organizations who use our models to aid their decision making process.')
])
],
),
dbc.Row([
get_card(collaborators[i]) for i in range(len(collaborators))
]),
],
)
return html.Div([Navbar(), body, Footer()], className="site") | 0.409929 | 0.105073 |
import numpy as np
import plot_schema
import matplotlib.pyplot as plt
class PlotsNine():
'''
classdocs
'''
def __init__(self, directory, full=True):
'''
Constructor
'''
self.t_gap_ms = 5.0
self.directory = directory
self.full = full
if self.full:
self.electrodes = ['electrode#000448302', 'electrode#000451300',
'electrode#000452730', 'electrode#000453393',
'electrode#000457525', 'electrode#000458894',
'electrode#000438028', 'electrode#000460291']
else:
self.electrodes = ['electrode#000094150', 'electrode#000092294']
self.period_ms = 1000
self.template = plot_schema.PlotSchema()
def load_data(self):
n_data_path = self.directory
self.n_data = self.load_case_data(n_data_path)
def load_case_data(self, case_path):
n_electrodes = len(self.electrodes)
for ii in range(n_electrodes):
electrode_path = case_path + '/' + self.electrodes[ii]
temp_data = np.loadtxt(electrode_path)
if ii == 0:
n_times = temp_data.size
data = np.zeros((n_times, n_electrodes))
data[:, ii] = temp_data[:]
return data
def set_ECG_type(self, ECG_lead, flipper=1):
''' SETUP plot vectors for each of the different ECG types
'''
if self.full:
lead_1 = 7
lead_2 = 8
else:
lead_1 = 1
lead_2 = 2
ECG_type = ECG_lead - 1
assert((len(self.electrodes) >= ECG_type))
n_points = self.n_data[:, 0].size
# 1 setup time series
max_time = self.t_gap_ms / 1000 * n_points
self.time = np.linspace(0, max_time, n_points)
# first normalise
if ECG_type == -1:
col_1 = lead_1 - 1
col_2 = lead_2 - 1
self.n_ECG_data = flipper * (self.n_data[:, col_1] -
self.n_data[:, col_2])
self.y_label = r'$ \Delta V$'
else:
self.n_ECG_data = flipper * self.n_data[:, ECG_type]
self.y_label = r'$ V$'
def plot_normal_ECG_final(self, save_file):
""" """
index_end = self.time.size / 2
index_start = 0
self.template.apply_fontsettings(plt)
f = plt.figure()
self.template.apply_figuresize_settings(f)
axes = plt.axes()
plt.grid()
plt.plot(self.time[index_start:index_end],
self.n_ECG_data[index_start:index_end])
plt.xlabel('$t (s)$', fontsize=14)
plt.ylabel(self.y_label, fontsize=14, rotation='horizontal')
self.template.apply_figuresize_settings(f)
for x_ticl_i in axes.get_xticklabels():
x_ticl_i.set_fontsize(14)
for y_ticl_i in axes.get_yticklabels():
y_ticl_i.set_fontsize(14)
save_loc = self.directory + '/' + save_file
plt.savefig(save_loc, dpi=100, bbox_inches='tight')
def plot_normal_ECG_full(self, save_file):
self.template.apply_fontsettings(plt)
f = plt.figure()
self.template.apply_figuresize_settings(f)
axes = plt.axes()
plt.grid()
plt.plot(self.time, self.n_ECG_data)
plt.xlabel('$t (s)$', fontsize=14)
plt.ylabel(self.y_label, fontsize=14, rotation='horizontal')
self.template.apply_figuresize_settings(f)
for x_ticl_i in axes.get_xticklabels():
x_ticl_i.set_fontsize(14)
for y_ticl_i in axes.get_yticklabels():
y_ticl_i.set_fontsize(14)
save_loc = self.directory + '/' + save_file
plt.savefig(save_loc, dpi=100, bbox_inches='tight')
plt.show() | tools/cardiac_py/experiments/nine.py | import numpy as np
import plot_schema
import matplotlib.pyplot as plt
class PlotsNine():
'''
classdocs
'''
def __init__(self, directory, full=True):
'''
Constructor
'''
self.t_gap_ms = 5.0
self.directory = directory
self.full = full
if self.full:
self.electrodes = ['electrode#000448302', 'electrode#000451300',
'electrode#000452730', 'electrode#000453393',
'electrode#000457525', 'electrode#000458894',
'electrode#000438028', 'electrode#000460291']
else:
self.electrodes = ['electrode#000094150', 'electrode#000092294']
self.period_ms = 1000
self.template = plot_schema.PlotSchema()
def load_data(self):
n_data_path = self.directory
self.n_data = self.load_case_data(n_data_path)
def load_case_data(self, case_path):
n_electrodes = len(self.electrodes)
for ii in range(n_electrodes):
electrode_path = case_path + '/' + self.electrodes[ii]
temp_data = np.loadtxt(electrode_path)
if ii == 0:
n_times = temp_data.size
data = np.zeros((n_times, n_electrodes))
data[:, ii] = temp_data[:]
return data
def set_ECG_type(self, ECG_lead, flipper=1):
''' SETUP plot vectors for each of the different ECG types
'''
if self.full:
lead_1 = 7
lead_2 = 8
else:
lead_1 = 1
lead_2 = 2
ECG_type = ECG_lead - 1
assert((len(self.electrodes) >= ECG_type))
n_points = self.n_data[:, 0].size
# 1 setup time series
max_time = self.t_gap_ms / 1000 * n_points
self.time = np.linspace(0, max_time, n_points)
# first normalise
if ECG_type == -1:
col_1 = lead_1 - 1
col_2 = lead_2 - 1
self.n_ECG_data = flipper * (self.n_data[:, col_1] -
self.n_data[:, col_2])
self.y_label = r'$ \Delta V$'
else:
self.n_ECG_data = flipper * self.n_data[:, ECG_type]
self.y_label = r'$ V$'
def plot_normal_ECG_final(self, save_file):
""" """
index_end = self.time.size / 2
index_start = 0
self.template.apply_fontsettings(plt)
f = plt.figure()
self.template.apply_figuresize_settings(f)
axes = plt.axes()
plt.grid()
plt.plot(self.time[index_start:index_end],
self.n_ECG_data[index_start:index_end])
plt.xlabel('$t (s)$', fontsize=14)
plt.ylabel(self.y_label, fontsize=14, rotation='horizontal')
self.template.apply_figuresize_settings(f)
for x_ticl_i in axes.get_xticklabels():
x_ticl_i.set_fontsize(14)
for y_ticl_i in axes.get_yticklabels():
y_ticl_i.set_fontsize(14)
save_loc = self.directory + '/' + save_file
plt.savefig(save_loc, dpi=100, bbox_inches='tight')
def plot_normal_ECG_full(self, save_file):
self.template.apply_fontsettings(plt)
f = plt.figure()
self.template.apply_figuresize_settings(f)
axes = plt.axes()
plt.grid()
plt.plot(self.time, self.n_ECG_data)
plt.xlabel('$t (s)$', fontsize=14)
plt.ylabel(self.y_label, fontsize=14, rotation='horizontal')
self.template.apply_figuresize_settings(f)
for x_ticl_i in axes.get_xticklabels():
x_ticl_i.set_fontsize(14)
for y_ticl_i in axes.get_yticklabels():
y_ticl_i.set_fontsize(14)
save_loc = self.directory + '/' + save_file
plt.savefig(save_loc, dpi=100, bbox_inches='tight')
plt.show() | 0.437824 | 0.36869 |
from pathlib import Path
import datetime
from dataclasses import dataclass
IVMS_FOLDER = Path(r'.\\data_files\\IVMS')
DRIVER_TRAINING = Path(r'.\\data_files\\IVMS\\driver_training_db.xlsx')
DATABASE = r'ivms_db.sqlite3'
@dataclass
class IvmsVehicle:
asset_descr: str
registration: str
make: str
model: str
year_manufacture: str
chassis_number: str
date_ras: datetime.datetime
@dataclass
class IvmsDriver:
contractor: int = None
employee_no: int = None
ivms_id: int = None
name: str = None
dob: datetime.datetime = None
mobile: str = None
hse_passport: str = None
site_name: str = None
ROP_license: str = None
date_issue_license: datetime.datetime = None
date_expiry_license: datetime.datetime = None
PDO_permit: str = None
date_expiry_permit: datetime.datetime = None
vehicle_light: str = None
vehicle_heavy: str = None
date_dd01: datetime.datetime = None
date_dd02: datetime.datetime = None
date_dd03: datetime.datetime = None
date_dd04: datetime.datetime = None
date_dd05: datetime.datetime = None
date_dd06: datetime.datetime = None
date_dd06_due: datetime.datetime = None
date_assessment_day: datetime.datetime = None
date_assessment_night: datetime.datetime = None
date_assessment_rough: datetime.datetime = None
assessment_comment: str = None
training_comment: str = None
@dataclass
class IvmsFileTripReport:
file_name: str = None
file_date: datetime.datetime = None
@dataclass
class IvmsTripReport:
id_file: int = None
id_vehicle: int = None
report_date: datetime.datetime = None
driving_time: datetime.time = None
standing_time: datetime.time = None
duration: datetime.time = None
idle_time: datetime.time = None
distance: float = None
avg_speed: float = None
max_speed: float = None
@dataclass
class IvmsFileRag:
filename: str = None
file_date: datetime.datetime = None
@dataclass
class IvmsRag:
rag_report: datetime.datetime = None
id_file: int = None
id_driver: int = None
distance: float = None
driving_time: datetime.time = None
harsh_accel: int = None
harsh_brake: int = None
highest_speed: float = None
overspeeding_time: float = None
seatbelt_violation_time: datetime.time = None
accel_violation_score: float = None
decel_violation_score: float = None
seatbelt_violation_score: float = None
overspeeding_violation_score: float = None
total_score: float = None | ivms_settings.py | from pathlib import Path
import datetime
from dataclasses import dataclass
IVMS_FOLDER = Path(r'.\\data_files\\IVMS')
DRIVER_TRAINING = Path(r'.\\data_files\\IVMS\\driver_training_db.xlsx')
DATABASE = r'ivms_db.sqlite3'
@dataclass
class IvmsVehicle:
asset_descr: str
registration: str
make: str
model: str
year_manufacture: str
chassis_number: str
date_ras: datetime.datetime
@dataclass
class IvmsDriver:
contractor: int = None
employee_no: int = None
ivms_id: int = None
name: str = None
dob: datetime.datetime = None
mobile: str = None
hse_passport: str = None
site_name: str = None
ROP_license: str = None
date_issue_license: datetime.datetime = None
date_expiry_license: datetime.datetime = None
PDO_permit: str = None
date_expiry_permit: datetime.datetime = None
vehicle_light: str = None
vehicle_heavy: str = None
date_dd01: datetime.datetime = None
date_dd02: datetime.datetime = None
date_dd03: datetime.datetime = None
date_dd04: datetime.datetime = None
date_dd05: datetime.datetime = None
date_dd06: datetime.datetime = None
date_dd06_due: datetime.datetime = None
date_assessment_day: datetime.datetime = None
date_assessment_night: datetime.datetime = None
date_assessment_rough: datetime.datetime = None
assessment_comment: str = None
training_comment: str = None
@dataclass
class IvmsFileTripReport:
file_name: str = None
file_date: datetime.datetime = None
@dataclass
class IvmsTripReport:
id_file: int = None
id_vehicle: int = None
report_date: datetime.datetime = None
driving_time: datetime.time = None
standing_time: datetime.time = None
duration: datetime.time = None
idle_time: datetime.time = None
distance: float = None
avg_speed: float = None
max_speed: float = None
@dataclass
class IvmsFileRag:
filename: str = None
file_date: datetime.datetime = None
@dataclass
class IvmsRag:
rag_report: datetime.datetime = None
id_file: int = None
id_driver: int = None
distance: float = None
driving_time: datetime.time = None
harsh_accel: int = None
harsh_brake: int = None
highest_speed: float = None
overspeeding_time: float = None
seatbelt_violation_time: datetime.time = None
accel_violation_score: float = None
decel_violation_score: float = None
seatbelt_violation_score: float = None
overspeeding_violation_score: float = None
total_score: float = None | 0.670608 | 0.165458 |
import logging
import requests
from lxml import html
from collections import namedtuple
from datetime import datetime
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
XP_USAGE_SINCE = '//*[@id="main"]/div/section/' \
'div[2]/section[1]/div/h2/text()'
XP_USAGE_TOTAL = '//*[@id="main"]/div/section/' \
'div[2]/section[1]/div/div/div/strong/text()'
XP_ACCOUNT_BALANCE = '//*[@id="main"]/div/section/' \
'div[1]/section[1]/div/span/text()'
XP_BUNDLE_NAME = '//*[@id="main"]/div/section/' \
'div[2]/section[2]/div/div[1]/div[1]/ul[1]/li/text()'
# 'My Usage' page:
XP_USAGE_TOTAL_DATA_USED = '//*[@id="main"]/div[1]/' \
'section/div[2]/dl/dd[4]/strong/text()'
XP_USAGE_DATA_UPLOADED = '//*[@id="main"]/div[1]/' \
'section/div[2]/dl/dd[3]/text()'
XP_USAGE_DATA_DOWNLOADED = '//*[@id="main"]/div[1]/' \
'section/div[2]/dl/dd[2]/text()'
XP_TIME_SPENT_ONLINE = '//*[@id="main"]/div[1]/' \
'section/div[2]/dl/dd[1]/text()'
XP_USAGE_UPDATED = '//*[@id="main"]/div[1]/' \
'section/div[2]/p/text()'
# 'My Usage' page 'Your Broadband Logins' table
XP_LOGINS_TABLE_BASE = '//*[@id="main"]/div[1]/' \
'section/div[3]/table/tbody/tr[1]/'
XP_USAGE_DATA_DOWNLOADED_TODAY_SO_FAR = '{}td[6]/text()'.format(
XP_LOGINS_TABLE_BASE)
XP_USAGE_DATA_UPLOADED_TODAY_SO_FAR = '{}td[5]/text()'.format(
XP_LOGINS_TABLE_BASE)
XP_USAGE_ONLINE_TIME_TODAY = '{}td[4]/text()'.format(XP_LOGINS_TABLE_BASE)
XP_USAGE_IP_ADDRESS_TODAY = '{}td[3]/text()'.format(XP_LOGINS_TABLE_BASE)
XP_USAGE_ENDED_TIME_TODAY = '{}td[2]/text()'.format(XP_LOGINS_TABLE_BASE)
XP_USAGE_STARTED_TIME_TODAY = '{}td[1]/text()'.format(XP_LOGINS_TABLE_BASE)
# Bill period dropdown
XP_USAGE_PERIOD_CURRENT = '//*[@id="billing-period"]/option[1]/text()'
DEFAULT_FAIR_USAGE_LIMIT_GB = 1024
DATA_KILOBYTES = "kB"
DATA_MEGABYTES = "MB"
DATA_GIGABYTES = "GB"
DATA_TERABYTES = "TB"
UNKNOWN_VALUE = ""
class Account:
"""
Represents a VF Account.
"""
def __init__(self, username, password, token1, token2,
fair_usage_limit=DEFAULT_FAIR_USAGE_LIMIT_GB):
"""
Defines an vf account.
:param username: VF Broadband username (email)
:param password: VF Broadband password
:param token1: Token 1
:param token2: Token 2
:param fair_usage_limit: If your fair usage is
not 1000 GB, specify it here.
"""
log.debug("Initialising new VF Account")
if "@" not in username:
log.warning("Vodafone Broadband username "
"should be an email address.")
self.logged_in = False
self.overview_data = None
self.data = None
self.username = username
self.password = password
self.verification_token1 = token1
self.verification_token2 = token2
self.fair_usage_limit = fair_usage_limit
def init_login(self):
""" Do the account overview request and return account tuple """
self._session = requests.Session()
self._session.get('https://n.vodafone'
'.ie/en.html')
data = '{"userName":"' + self.username + '"}'
self._session.post('https://n.vodafone.ie/'
'bin/mvc.do/credential/check/mml',
data=data)
params = (
('t', '1'),
)
log.debug(f"self.username {self.username}")
log.debug(f"self.verification_token1 {self.verification_token1}")
log.debug(f"self.verification_token2 {self.verification_token2}")
data = {
'__RequestVerificationToken': self.verification_token2,
'emailAddress': self.username,
'password': <PASSWORD>
}
response = self._session.post('https://broadband.'
'vodafone.ie/myaccount/session/login',
headers=self.get_headers(),
cookies=self.get_cookies(),
params=params,
data=data
)
# usage since date
# e.g. ['Since 15 Apr 2020']
usage_since = self.get_xpath_value(response, XP_USAGE_SINCE)
# data usage. e.g. ['397.35 GB']
usage_value_raw = self.get_xpath_value(response, XP_USAGE_TOTAL)
usage_value, usage_value_unit, usage_percent, usage_value_mb = \
self.get_usage_values(usage_value_raw)
# account due fee. e.g. €60
account_balance = self.get_xpath_value(response, XP_ACCOUNT_BALANCE)
# Bundles
# Gigabit Broadband 300 (eir)
bundle_name = self.get_xpath_value(response, XP_BUNDLE_NAME)
if usage_value_raw == UNKNOWN_VALUE:
log.warning("Unable to get usage data.")
# log.warning(response.content)
else:
AccountDetails = namedtuple("AccountDetails",
["usage_since",
"usage_value",
"usage_value_raw",
"usage_value_unit",
"usage_percent",
"last_updated",
"account_balance",
"bundle_name"])
account_details = AccountDetails(usage_since,
usage_value,
usage_value_raw,
usage_value_unit,
usage_percent,
datetime.now(),
account_balance,
bundle_name)
log.debug(account_details)
self.logged_in = True
self.overview_data = account_details
return account_details
return None
# flake8: noqa: E501
def get_account_usage_request(self):
""" Do the account usage request and return account tuple """
self.init_login()
response = self._session.get('https://broadband.vodafone.'
'ie/myaccount/usage',
headers=self.get_headers(),
cookies=self.get_cookies()
)
log.info("'Your Broadband Usage' in result? {}".format(
"Your Broadband Usage" in response.text))
if "Error Occurred" in response.text:
log.error("‼️ 'Error Occurred' in response.")
if "Your Broadband Usage" in response.text:
log.info("✅ Looking good. 'Your Broadband Usage' in result.")
bill_period = self.get_xpath_value(
response, XP_USAGE_PERIOD_CURRENT)
total_used_value, total_used_unit, total_used_percent, total_used_value_mb = self.get_usage_values(
self.get_xpath_value(response, XP_USAGE_TOTAL_DATA_USED))
total_uploaded_value, total_uploaded_used_unit, total_uploaded_used_percent, total_uploaded_value_mb = \
self.get_usage_values(
self.get_xpath_value(response, XP_USAGE_DATA_UPLOADED))
total_downloaded_value, total_downloaded_used_unit, total_downloaded_used_percent, total_downloaded_value_mb = \
self.get_usage_values(
self.get_xpath_value(response, XP_USAGE_DATA_DOWNLOADED))
total_time_spent_online = self.get_xpath_value(
response, XP_TIME_SPENT_ONLINE)
total_updated_time = self.get_xpath_value(
response, XP_USAGE_UPDATED)
today_downloaded_value, today_downloaded_used_unit, today_downloaded_used_percent, today_downloaded_value_mb = \
self.get_usage_values(
self.get_xpath_value(response, XP_USAGE_DATA_DOWNLOADED_TODAY_SO_FAR))
today_uploaded_value, today_uploaded_used_unit, today_uploaded_used_percent, today_uploaded_value_mb = \
self.get_usage_values(
self.get_xpath_value(response, XP_USAGE_DATA_UPLOADED_TODAY_SO_FAR))
today_ip_address = self.get_xpath_value(
response, XP_USAGE_IP_ADDRESS_TODAY)
today_online_time = self.get_xpath_value(
response, XP_USAGE_ONLINE_TIME_TODAY)
AccountUsageDetails = namedtuple("AccountUsageDetails",
["bill_period",
"total_time_spent_online",
"total_used_value",
"total_used_value_mb",
"total_used_unit",
"total_used_percent",
"last_updated",
"total_uploaded_value",
"total_uploaded_value_mb",
"total_uploaded_used_unit",
"total_downloaded_value",
"total_downloaded_value_mb",
"total_downloaded_used_unit",
"total_updated_time",
"today_downloaded_value",
"today_downloaded_value_mb",
"today_downloaded_used_unit",
"today_uploaded_value",
"today_uploaded_value_mb",
"today_uploaded_used_unit",
"today_ip_address",
"today_online_time"
])
account_usage_details = AccountUsageDetails(bill_period,
total_time_spent_online,
total_used_value,
total_used_value_mb,
total_used_unit,
total_used_percent,
datetime.now(),
total_uploaded_value,
total_uploaded_value_mb,
total_uploaded_used_unit,
total_downloaded_value,
total_downloaded_value_mb,
total_downloaded_used_unit,
total_updated_time,
today_downloaded_value,
today_downloaded_value_mb,
today_downloaded_used_unit,
today_uploaded_value,
today_uploaded_value_mb,
today_uploaded_used_unit,
today_ip_address,
today_online_time)
log.debug(account_usage_details)
self.logged_in = True
self.data = account_usage_details
return account_usage_details
return None
def get_cookies(self):
cookies = self._session.cookies
# log.debug("cookies now: {}".format(self._session.cookies))
cookies['__RequestVerificationToken'] = <PASSWORD>.verification_token1
return cookies
def get_headers(self):
return {
'Connection': 'keep-alive',
'Cache-Control': 'max-age=0',
'Origin': 'https://broadband.vodafone.ie',
'Upgrade-Insecure-Requests': '1',
'DNT': '1',
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Macintosh; '
'Intel Mac OS X 10_15_4) '
'AppleWebKit/537.36 (KHTML, '
'like Gecko) Chrome/81.0.4044.129 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml'
',application/xml;q=0.9,image/webp,'
'image/apng,*/*;q=0.8,application/'
'signed-exchange;v=b3;q=0.9',
'Sec-Fetch-Site': 'same-origin',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-User': '?1',
'Sec-Fetch-Dest': 'document',
'Referer': 'https://broadband.vodafone.ie'
'/myaccount/session/login?t=1',
'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8',
}
def get_xpath_value(self, response, path):
""" Returns first result of xpath
match, or UNKNOWN_VALUE if not found. """
tree = html.fromstring(response.content)
try:
result = tree.xpath(path)
if len(result) == 0:
log.warning(f"xpath not found: {path}")
return UNKNOWN_VALUE
return result[0]
except ValueError:
log.warning(f"xpath not found: {path}")
return UNKNOWN_VALUE
def is_logged_in(self):
"""Returns true if a successful login has happened"""
return self.logged_in
def get_usage_values(self, usage_value_raw):
""" Get usage values. """
try:
usage_value = usage_value_raw.replace(',', '').split(' ')[0]
usage_value_unit = self.get_unit(usage_value_raw.split(' ')[1])
usage_percent = int((float(usage_value) /
self.fair_usage_limit) * 100)
if usage_value_unit == DATA_MEGABYTES:
usage_value_mb = usage_value
elif usage_value_unit == DATA_GIGABYTES:
usage_value_mb = float(usage_value) * 1024
elif usage_value_unit == DATA_TERABYTES:
usage_value_mb = float(usage_value) * 1024 * 1024
else:
log.warning(f"Unable to determine usage_value_mb. usage_value_unit: {usage_value_unit}")
usage_value_mb = None
return usage_value, usage_value_unit, usage_percent, usage_value_mb
except Exception:
log.error(
"Unable to calculate usage. usage_value_raw: {}".format(usage_value_raw))
return None, None, None, None
def get_unit(self, unit_string):
value = unit_string.upper()
if value == "KB":
return DATA_KILOBYTES
if value == "MB":
return DATA_MEGABYTES
if value == "GB":
return DATA_GIGABYTES
if value == "TB":
return DATA_TERABYTES | vodafone_ie_account_checker/api.py |
import logging
import requests
from lxml import html
from collections import namedtuple
from datetime import datetime
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
XP_USAGE_SINCE = '//*[@id="main"]/div/section/' \
'div[2]/section[1]/div/h2/text()'
XP_USAGE_TOTAL = '//*[@id="main"]/div/section/' \
'div[2]/section[1]/div/div/div/strong/text()'
XP_ACCOUNT_BALANCE = '//*[@id="main"]/div/section/' \
'div[1]/section[1]/div/span/text()'
XP_BUNDLE_NAME = '//*[@id="main"]/div/section/' \
'div[2]/section[2]/div/div[1]/div[1]/ul[1]/li/text()'
# 'My Usage' page:
XP_USAGE_TOTAL_DATA_USED = '//*[@id="main"]/div[1]/' \
'section/div[2]/dl/dd[4]/strong/text()'
XP_USAGE_DATA_UPLOADED = '//*[@id="main"]/div[1]/' \
'section/div[2]/dl/dd[3]/text()'
XP_USAGE_DATA_DOWNLOADED = '//*[@id="main"]/div[1]/' \
'section/div[2]/dl/dd[2]/text()'
XP_TIME_SPENT_ONLINE = '//*[@id="main"]/div[1]/' \
'section/div[2]/dl/dd[1]/text()'
XP_USAGE_UPDATED = '//*[@id="main"]/div[1]/' \
'section/div[2]/p/text()'
# 'My Usage' page 'Your Broadband Logins' table
XP_LOGINS_TABLE_BASE = '//*[@id="main"]/div[1]/' \
'section/div[3]/table/tbody/tr[1]/'
XP_USAGE_DATA_DOWNLOADED_TODAY_SO_FAR = '{}td[6]/text()'.format(
XP_LOGINS_TABLE_BASE)
XP_USAGE_DATA_UPLOADED_TODAY_SO_FAR = '{}td[5]/text()'.format(
XP_LOGINS_TABLE_BASE)
XP_USAGE_ONLINE_TIME_TODAY = '{}td[4]/text()'.format(XP_LOGINS_TABLE_BASE)
XP_USAGE_IP_ADDRESS_TODAY = '{}td[3]/text()'.format(XP_LOGINS_TABLE_BASE)
XP_USAGE_ENDED_TIME_TODAY = '{}td[2]/text()'.format(XP_LOGINS_TABLE_BASE)
XP_USAGE_STARTED_TIME_TODAY = '{}td[1]/text()'.format(XP_LOGINS_TABLE_BASE)
# Bill period dropdown
XP_USAGE_PERIOD_CURRENT = '//*[@id="billing-period"]/option[1]/text()'
DEFAULT_FAIR_USAGE_LIMIT_GB = 1024
DATA_KILOBYTES = "kB"
DATA_MEGABYTES = "MB"
DATA_GIGABYTES = "GB"
DATA_TERABYTES = "TB"
UNKNOWN_VALUE = ""
class Account:
"""
Represents a VF Account.
"""
def __init__(self, username, password, token1, token2,
fair_usage_limit=DEFAULT_FAIR_USAGE_LIMIT_GB):
"""
Defines an vf account.
:param username: VF Broadband username (email)
:param password: VF Broadband password
:param token1: Token 1
:param token2: Token 2
:param fair_usage_limit: If your fair usage is
not 1000 GB, specify it here.
"""
log.debug("Initialising new VF Account")
if "@" not in username:
log.warning("Vodafone Broadband username "
"should be an email address.")
self.logged_in = False
self.overview_data = None
self.data = None
self.username = username
self.password = password
self.verification_token1 = token1
self.verification_token2 = token2
self.fair_usage_limit = fair_usage_limit
def init_login(self):
""" Do the account overview request and return account tuple """
self._session = requests.Session()
self._session.get('https://n.vodafone'
'.ie/en.html')
data = '{"userName":"' + self.username + '"}'
self._session.post('https://n.vodafone.ie/'
'bin/mvc.do/credential/check/mml',
data=data)
params = (
('t', '1'),
)
log.debug(f"self.username {self.username}")
log.debug(f"self.verification_token1 {self.verification_token1}")
log.debug(f"self.verification_token2 {self.verification_token2}")
data = {
'__RequestVerificationToken': self.verification_token2,
'emailAddress': self.username,
'password': <PASSWORD>
}
response = self._session.post('https://broadband.'
'vodafone.ie/myaccount/session/login',
headers=self.get_headers(),
cookies=self.get_cookies(),
params=params,
data=data
)
# usage since date
# e.g. ['Since 15 Apr 2020']
usage_since = self.get_xpath_value(response, XP_USAGE_SINCE)
# data usage. e.g. ['397.35 GB']
usage_value_raw = self.get_xpath_value(response, XP_USAGE_TOTAL)
usage_value, usage_value_unit, usage_percent, usage_value_mb = \
self.get_usage_values(usage_value_raw)
# account due fee. e.g. €60
account_balance = self.get_xpath_value(response, XP_ACCOUNT_BALANCE)
# Bundles
# Gigabit Broadband 300 (eir)
bundle_name = self.get_xpath_value(response, XP_BUNDLE_NAME)
if usage_value_raw == UNKNOWN_VALUE:
log.warning("Unable to get usage data.")
# log.warning(response.content)
else:
AccountDetails = namedtuple("AccountDetails",
["usage_since",
"usage_value",
"usage_value_raw",
"usage_value_unit",
"usage_percent",
"last_updated",
"account_balance",
"bundle_name"])
account_details = AccountDetails(usage_since,
usage_value,
usage_value_raw,
usage_value_unit,
usage_percent,
datetime.now(),
account_balance,
bundle_name)
log.debug(account_details)
self.logged_in = True
self.overview_data = account_details
return account_details
return None
# flake8: noqa: E501
def get_account_usage_request(self):
""" Do the account usage request and return account tuple """
self.init_login()
response = self._session.get('https://broadband.vodafone.'
'ie/myaccount/usage',
headers=self.get_headers(),
cookies=self.get_cookies()
)
log.info("'Your Broadband Usage' in result? {}".format(
"Your Broadband Usage" in response.text))
if "Error Occurred" in response.text:
log.error("‼️ 'Error Occurred' in response.")
if "Your Broadband Usage" in response.text:
log.info("✅ Looking good. 'Your Broadband Usage' in result.")
bill_period = self.get_xpath_value(
response, XP_USAGE_PERIOD_CURRENT)
total_used_value, total_used_unit, total_used_percent, total_used_value_mb = self.get_usage_values(
self.get_xpath_value(response, XP_USAGE_TOTAL_DATA_USED))
total_uploaded_value, total_uploaded_used_unit, total_uploaded_used_percent, total_uploaded_value_mb = \
self.get_usage_values(
self.get_xpath_value(response, XP_USAGE_DATA_UPLOADED))
total_downloaded_value, total_downloaded_used_unit, total_downloaded_used_percent, total_downloaded_value_mb = \
self.get_usage_values(
self.get_xpath_value(response, XP_USAGE_DATA_DOWNLOADED))
total_time_spent_online = self.get_xpath_value(
response, XP_TIME_SPENT_ONLINE)
total_updated_time = self.get_xpath_value(
response, XP_USAGE_UPDATED)
today_downloaded_value, today_downloaded_used_unit, today_downloaded_used_percent, today_downloaded_value_mb = \
self.get_usage_values(
self.get_xpath_value(response, XP_USAGE_DATA_DOWNLOADED_TODAY_SO_FAR))
today_uploaded_value, today_uploaded_used_unit, today_uploaded_used_percent, today_uploaded_value_mb = \
self.get_usage_values(
self.get_xpath_value(response, XP_USAGE_DATA_UPLOADED_TODAY_SO_FAR))
today_ip_address = self.get_xpath_value(
response, XP_USAGE_IP_ADDRESS_TODAY)
today_online_time = self.get_xpath_value(
response, XP_USAGE_ONLINE_TIME_TODAY)
AccountUsageDetails = namedtuple("AccountUsageDetails",
["bill_period",
"total_time_spent_online",
"total_used_value",
"total_used_value_mb",
"total_used_unit",
"total_used_percent",
"last_updated",
"total_uploaded_value",
"total_uploaded_value_mb",
"total_uploaded_used_unit",
"total_downloaded_value",
"total_downloaded_value_mb",
"total_downloaded_used_unit",
"total_updated_time",
"today_downloaded_value",
"today_downloaded_value_mb",
"today_downloaded_used_unit",
"today_uploaded_value",
"today_uploaded_value_mb",
"today_uploaded_used_unit",
"today_ip_address",
"today_online_time"
])
account_usage_details = AccountUsageDetails(bill_period,
total_time_spent_online,
total_used_value,
total_used_value_mb,
total_used_unit,
total_used_percent,
datetime.now(),
total_uploaded_value,
total_uploaded_value_mb,
total_uploaded_used_unit,
total_downloaded_value,
total_downloaded_value_mb,
total_downloaded_used_unit,
total_updated_time,
today_downloaded_value,
today_downloaded_value_mb,
today_downloaded_used_unit,
today_uploaded_value,
today_uploaded_value_mb,
today_uploaded_used_unit,
today_ip_address,
today_online_time)
log.debug(account_usage_details)
self.logged_in = True
self.data = account_usage_details
return account_usage_details
return None
def get_cookies(self):
cookies = self._session.cookies
# log.debug("cookies now: {}".format(self._session.cookies))
cookies['__RequestVerificationToken'] = <PASSWORD>.verification_token1
return cookies
def get_headers(self):
return {
'Connection': 'keep-alive',
'Cache-Control': 'max-age=0',
'Origin': 'https://broadband.vodafone.ie',
'Upgrade-Insecure-Requests': '1',
'DNT': '1',
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Macintosh; '
'Intel Mac OS X 10_15_4) '
'AppleWebKit/537.36 (KHTML, '
'like Gecko) Chrome/81.0.4044.129 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml'
',application/xml;q=0.9,image/webp,'
'image/apng,*/*;q=0.8,application/'
'signed-exchange;v=b3;q=0.9',
'Sec-Fetch-Site': 'same-origin',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-User': '?1',
'Sec-Fetch-Dest': 'document',
'Referer': 'https://broadband.vodafone.ie'
'/myaccount/session/login?t=1',
'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8',
}
def get_xpath_value(self, response, path):
""" Returns first result of xpath
match, or UNKNOWN_VALUE if not found. """
tree = html.fromstring(response.content)
try:
result = tree.xpath(path)
if len(result) == 0:
log.warning(f"xpath not found: {path}")
return UNKNOWN_VALUE
return result[0]
except ValueError:
log.warning(f"xpath not found: {path}")
return UNKNOWN_VALUE
def is_logged_in(self):
"""Returns true if a successful login has happened"""
return self.logged_in
def get_usage_values(self, usage_value_raw):
""" Get usage values. """
try:
usage_value = usage_value_raw.replace(',', '').split(' ')[0]
usage_value_unit = self.get_unit(usage_value_raw.split(' ')[1])
usage_percent = int((float(usage_value) /
self.fair_usage_limit) * 100)
if usage_value_unit == DATA_MEGABYTES:
usage_value_mb = usage_value
elif usage_value_unit == DATA_GIGABYTES:
usage_value_mb = float(usage_value) * 1024
elif usage_value_unit == DATA_TERABYTES:
usage_value_mb = float(usage_value) * 1024 * 1024
else:
log.warning(f"Unable to determine usage_value_mb. usage_value_unit: {usage_value_unit}")
usage_value_mb = None
return usage_value, usage_value_unit, usage_percent, usage_value_mb
except Exception:
log.error(
"Unable to calculate usage. usage_value_raw: {}".format(usage_value_raw))
return None, None, None, None
def get_unit(self, unit_string):
value = unit_string.upper()
if value == "KB":
return DATA_KILOBYTES
if value == "MB":
return DATA_MEGABYTES
if value == "GB":
return DATA_GIGABYTES
if value == "TB":
return DATA_TERABYTES | 0.323594 | 0.049017 |
import argparse
import os
import random
import pandas as pd
import numpy as np
lang_families = {'arz': 'Afro-Asiatic', 'afb': 'Afro-Asiatic', 'ara': 'Afro-Asiatic', 'syc': 'Afro-Asiatic',
'heb': 'Afro-Asiatic', 'amh': 'Afro-Asiatic',
'gup': 'Arnhem',
'aym': 'Aymaran', 'cni': 'Arawakan', 'ame': 'Arawakan',
'see': 'Iroquoian',
'sah': 'Turkic', 'tyv': 'Turkic',
'itl': 'Chukotko-Kamchatkan', 'ckt': 'Chukotko-Kamchatkan',
'evn': 'Tungusic',
'ckb': 'Indo-European', 'kmr': 'Indo-European', 'pol': 'Indo-European', 'rus': 'Indo-European',
'ces': 'Indo-European', 'bul': 'Indo-European', 'deu': 'Indo-European', 'nld': 'Indo-European',
'spa': 'Indo-European', 'por': 'Indo-European', 'bra': 'Indo-European', 'mag': 'Indo-European',
'ind': 'Austronesian', 'kod': 'Austronesian',
'ail': 'Trans–New Guinea',
'vep': 'Uralic', 'krl': 'Uralic', 'lud': 'Uralic', 'olo': 'Uralic'}
def add_lang_tag(tags, lang):
if lang != 'all':
family = lang_families[lang]
tags = f"{family};{lang};{tags}"
return tags
def gen_all_data(args):
languages = set(file.split('.')[0] for file in os.listdir(args.src_dir))
train_dfs = []
dev_dfs = []
for lang in languages:
train_file = os.path.join(args.src_dir, f"{lang}.hall")
dev_file = os.path.join(args.src_dir, f"{lang}.dev")
train = pd.read_csv(train_file, sep='\t', header=None, names=['lemma', 'infl', 'tags'])
dev = pd.read_csv(dev_file, sep='\t', header=None, names=['lemma', 'infl', 'tags'])
train['tags'] = train.apply(lambda x: add_lang_tag(x.tags, lang), axis=1)
dev['tags'] = dev.apply(lambda x: add_lang_tag(x.tags, lang), axis=1)
train = train.replace(np.nan, 'nan', regex=True)
dev = dev.replace(np.nan, 'nan', regex=True)
train_dfs.append(train)
dev_dfs.append(dev)
train_df = pd.concat(train_dfs)
dev_df = pd.concat(dev_dfs)
trg_train_file = os.path.join(args.trg_dir, 'all.train')
trg_dev_file = os.path.join(args.trg_dir, 'all.dev')
train_df.to_csv(trg_train_file, sep='\t', header=False, index=False)
dev_df.to_csv(trg_dev_file, sep='\t', header=False, index=False)
def gen_copy_data(df):
df_lemmas = df.drop_duplicates(subset=['lemma'])
df_lemmas['tags'] = df_lemmas.apply(lambda x: 'COPY', axis=1)
df_lemmas['infl'] = df_lemmas.apply(lambda x: x.lemma, axis=1)
df = pd.concat([df, df_lemmas])
return df
def gen_double_data(df):
df_lemmas = df.drop_duplicates(subset=['lemma'])
df_lemmas['tags'] = df_lemmas.apply(lambda x: 'DOUBLE', axis=1)
df_lemmas['infl'] = df_lemmas.apply(lambda x: str(x.lemma)+str(x.lemma), axis=1)
df = pd.concat([df, df_lemmas])
return df
def gen_tags_data(df):
df['lemma'] = df.apply(lambda x: x.infl, axis=1)
df['tags'] = df.apply(lambda x: 'COPY;' + x.tags)
return df
def change_first(lemma, infl, vocab):
letter = vocab[random.randint(0, len(vocab) - 1)]
lemma = letter + lemma[1:]
infl = letter + infl[1:]
return lemma, infl
def gen_first_letters(df):
chars = set()
for token in df.lemma:
chars |= set(token)
vocab = dict((i, c) for i, c in enumerate(chars))
first_letters = df[df.apply(lambda x: x['lemma'][0] == x['infl'][0], axis=1)]
first_letters[['lemma', 'infl']] = first_letters.apply(lambda x: change_first(x.lemma, x.infl, vocab),
axis=1, result_type="expand")
df = pd.concat([df, first_letters])
return df
def get_df(path):
df = pd.read_csv(path, sep='\t', header=None, names=['lemma', 'infl', 'tags'])
df = df.replace(np.nan, 'nan', regex=True)
return df
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--src_dir")
parser.add_argument("--trg_dir")
parser.add_argument("--copy", type=bool, default=False)
parser.add_argument("--lang")
parser.add_argument("--double_data", type=bool, default=False)
parser.add_argument("--first_letter", type=bool, default=False)
parser.add_argument("--gen_all", type=bool, default=False)
args = parser.parse_args()
if args.gen_all:
gen_all_data(args)
else:
path = os.path.join(args.src_dir, f'{args.lang}.train')
df = get_df(path)
if args.copy:
df = gen_copy_data(df)
if args.double_data:
df = gen_double_data(df)
if args.first_letter:
df = gen_first_letters(df)
if args.tags:
df = gen_tags_data(df)
target_file = os.path.join(args.trg_dir, f'{args.lang}.train')
df.to_csv(target_file, sep='\t', header=False, index=False)
if __name__ == '__main__':
main() | sigmorphon-2021/all_data/generate_data.py | import argparse
import os
import random
import pandas as pd
import numpy as np
lang_families = {'arz': 'Afro-Asiatic', 'afb': 'Afro-Asiatic', 'ara': 'Afro-Asiatic', 'syc': 'Afro-Asiatic',
'heb': 'Afro-Asiatic', 'amh': 'Afro-Asiatic',
'gup': 'Arnhem',
'aym': 'Aymaran', 'cni': 'Arawakan', 'ame': 'Arawakan',
'see': 'Iroquoian',
'sah': 'Turkic', 'tyv': 'Turkic',
'itl': 'Chukotko-Kamchatkan', 'ckt': 'Chukotko-Kamchatkan',
'evn': 'Tungusic',
'ckb': 'Indo-European', 'kmr': 'Indo-European', 'pol': 'Indo-European', 'rus': 'Indo-European',
'ces': 'Indo-European', 'bul': 'Indo-European', 'deu': 'Indo-European', 'nld': 'Indo-European',
'spa': 'Indo-European', 'por': 'Indo-European', 'bra': 'Indo-European', 'mag': 'Indo-European',
'ind': 'Austronesian', 'kod': 'Austronesian',
'ail': 'Trans–New Guinea',
'vep': 'Uralic', 'krl': 'Uralic', 'lud': 'Uralic', 'olo': 'Uralic'}
def add_lang_tag(tags, lang):
if lang != 'all':
family = lang_families[lang]
tags = f"{family};{lang};{tags}"
return tags
def gen_all_data(args):
languages = set(file.split('.')[0] for file in os.listdir(args.src_dir))
train_dfs = []
dev_dfs = []
for lang in languages:
train_file = os.path.join(args.src_dir, f"{lang}.hall")
dev_file = os.path.join(args.src_dir, f"{lang}.dev")
train = pd.read_csv(train_file, sep='\t', header=None, names=['lemma', 'infl', 'tags'])
dev = pd.read_csv(dev_file, sep='\t', header=None, names=['lemma', 'infl', 'tags'])
train['tags'] = train.apply(lambda x: add_lang_tag(x.tags, lang), axis=1)
dev['tags'] = dev.apply(lambda x: add_lang_tag(x.tags, lang), axis=1)
train = train.replace(np.nan, 'nan', regex=True)
dev = dev.replace(np.nan, 'nan', regex=True)
train_dfs.append(train)
dev_dfs.append(dev)
train_df = pd.concat(train_dfs)
dev_df = pd.concat(dev_dfs)
trg_train_file = os.path.join(args.trg_dir, 'all.train')
trg_dev_file = os.path.join(args.trg_dir, 'all.dev')
train_df.to_csv(trg_train_file, sep='\t', header=False, index=False)
dev_df.to_csv(trg_dev_file, sep='\t', header=False, index=False)
def gen_copy_data(df):
df_lemmas = df.drop_duplicates(subset=['lemma'])
df_lemmas['tags'] = df_lemmas.apply(lambda x: 'COPY', axis=1)
df_lemmas['infl'] = df_lemmas.apply(lambda x: x.lemma, axis=1)
df = pd.concat([df, df_lemmas])
return df
def gen_double_data(df):
df_lemmas = df.drop_duplicates(subset=['lemma'])
df_lemmas['tags'] = df_lemmas.apply(lambda x: 'DOUBLE', axis=1)
df_lemmas['infl'] = df_lemmas.apply(lambda x: str(x.lemma)+str(x.lemma), axis=1)
df = pd.concat([df, df_lemmas])
return df
def gen_tags_data(df):
df['lemma'] = df.apply(lambda x: x.infl, axis=1)
df['tags'] = df.apply(lambda x: 'COPY;' + x.tags)
return df
def change_first(lemma, infl, vocab):
letter = vocab[random.randint(0, len(vocab) - 1)]
lemma = letter + lemma[1:]
infl = letter + infl[1:]
return lemma, infl
def gen_first_letters(df):
chars = set()
for token in df.lemma:
chars |= set(token)
vocab = dict((i, c) for i, c in enumerate(chars))
first_letters = df[df.apply(lambda x: x['lemma'][0] == x['infl'][0], axis=1)]
first_letters[['lemma', 'infl']] = first_letters.apply(lambda x: change_first(x.lemma, x.infl, vocab),
axis=1, result_type="expand")
df = pd.concat([df, first_letters])
return df
def get_df(path):
df = pd.read_csv(path, sep='\t', header=None, names=['lemma', 'infl', 'tags'])
df = df.replace(np.nan, 'nan', regex=True)
return df
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--src_dir")
parser.add_argument("--trg_dir")
parser.add_argument("--copy", type=bool, default=False)
parser.add_argument("--lang")
parser.add_argument("--double_data", type=bool, default=False)
parser.add_argument("--first_letter", type=bool, default=False)
parser.add_argument("--gen_all", type=bool, default=False)
args = parser.parse_args()
if args.gen_all:
gen_all_data(args)
else:
path = os.path.join(args.src_dir, f'{args.lang}.train')
df = get_df(path)
if args.copy:
df = gen_copy_data(df)
if args.double_data:
df = gen_double_data(df)
if args.first_letter:
df = gen_first_letters(df)
if args.tags:
df = gen_tags_data(df)
target_file = os.path.join(args.trg_dir, f'{args.lang}.train')
df.to_csv(target_file, sep='\t', header=False, index=False)
if __name__ == '__main__':
main() | 0.35354 | 0.172538 |
__author__ = 'laifuyu'
import configparser
import sys
import mysql.connector
from globalpkg.global_var import logger
class MyDB:
"""动作类,获取数据库连接,配置数据库IP,端口等信息,获取数据库连接"""
def __init__(self, config_file, db):
config = configparser.ConfigParser()
# 从配置文件中读取数据库服务器IP、域名,端口
config.read(config_file, encoding='utf-8')
self.host = config[db]['host']
self.port = config[db]['port']
self.user = config[db]['user']
self.passwd = config[db]['passwd']
self.db_name = config[db]['db']
self.charset = config[db]['charset']
try:
self.dbconn = mysql.connector.connect(host=self.host, port=self.port, user=self.user, password=self.passwd, database=self.db_name, charset=self.charset)
except Exception as e:
logger.error('初始化数据连接失败:%s' % e)
sys.exit()
def get_host(self):
return self.host
def get_port(self):
return self.port
def get_conn(self):
return self.dbconn
def execute_create(self,query):
logger.info('query:%s' % query)
try:
db_cursor = self.dbconn.cursor()
db_cursor.execute(query)
db_cursor.execute('commit')
db_cursor.close()
return True
except Exception as e:
logger.error('创建数据库表操作失败:%s' % e)
db_cursor.execute('rollback')
db_cursor.close()
exit()
def execute_insert(self, query, data):
logger.info('query:%s data:%s' % (query, data))
try:
db_cursor = self.dbconn.cursor()
db_cursor.execute(query, data)
db_cursor.execute('commit')
db_cursor.close()
return True
except Exception as e:
logger.error('执行数据库插入操作失败:%s' % e)
db_cursor.execute('rollback')
db_cursor.close()
exit()
def execute_update(self, query, data):
query = query % data
logger.info('query:%s' % query)
try:
db_cursor = self.dbconn.cursor()
db_cursor.execute(query)
db_cursor.execute('commit')
db_cursor.close()
return ('',True)
except Exception as e:
logger.error('执行数据库更新操作失败:%s' % e)
db_cursor.execute('rollback')
db_cursor.close()
return (e, False)
def select_one_record(self, query, data=""):
'''返回结果只包含一条记录'''
logger.info('query:%s data:%s' % (query, data))
try:
db_cursor = self.dbconn.cursor()
if data:
db_cursor.execute(query, data)
else:
db_cursor.execute(query)
query_result = db_cursor.fetchone()
db_cursor.close()
return (query_result,True)
except Exception as e:
logger.error('执行数据库查询操作失败:%s' % e)
db_cursor.close()
return(e,False)
def select_many_record(self, query, data=""):
'''返回结果只包含多条记录'''
logger.info('query:%s data:%s' % (query, data))
try:
db_cursor = self.dbconn.cursor()
if data:
db_cursor.execute(query, data)
else:
db_cursor.execute(query)
query_result = db_cursor.fetchall()
db_cursor.close()
return query_result
except Exception as e:
logger.error('执行数据库查询操作失败:%s' % e)
db_cursor.close()
exit()
def close(self):
self.dbconn.close | globalpkg/mydb.py |
__author__ = 'laifuyu'
import configparser
import sys
import mysql.connector
from globalpkg.global_var import logger
class MyDB:
"""动作类,获取数据库连接,配置数据库IP,端口等信息,获取数据库连接"""
def __init__(self, config_file, db):
config = configparser.ConfigParser()
# 从配置文件中读取数据库服务器IP、域名,端口
config.read(config_file, encoding='utf-8')
self.host = config[db]['host']
self.port = config[db]['port']
self.user = config[db]['user']
self.passwd = config[db]['passwd']
self.db_name = config[db]['db']
self.charset = config[db]['charset']
try:
self.dbconn = mysql.connector.connect(host=self.host, port=self.port, user=self.user, password=self.passwd, database=self.db_name, charset=self.charset)
except Exception as e:
logger.error('初始化数据连接失败:%s' % e)
sys.exit()
def get_host(self):
return self.host
def get_port(self):
return self.port
def get_conn(self):
return self.dbconn
def execute_create(self,query):
logger.info('query:%s' % query)
try:
db_cursor = self.dbconn.cursor()
db_cursor.execute(query)
db_cursor.execute('commit')
db_cursor.close()
return True
except Exception as e:
logger.error('创建数据库表操作失败:%s' % e)
db_cursor.execute('rollback')
db_cursor.close()
exit()
def execute_insert(self, query, data):
logger.info('query:%s data:%s' % (query, data))
try:
db_cursor = self.dbconn.cursor()
db_cursor.execute(query, data)
db_cursor.execute('commit')
db_cursor.close()
return True
except Exception as e:
logger.error('执行数据库插入操作失败:%s' % e)
db_cursor.execute('rollback')
db_cursor.close()
exit()
def execute_update(self, query, data):
query = query % data
logger.info('query:%s' % query)
try:
db_cursor = self.dbconn.cursor()
db_cursor.execute(query)
db_cursor.execute('commit')
db_cursor.close()
return ('',True)
except Exception as e:
logger.error('执行数据库更新操作失败:%s' % e)
db_cursor.execute('rollback')
db_cursor.close()
return (e, False)
def select_one_record(self, query, data=""):
'''返回结果只包含一条记录'''
logger.info('query:%s data:%s' % (query, data))
try:
db_cursor = self.dbconn.cursor()
if data:
db_cursor.execute(query, data)
else:
db_cursor.execute(query)
query_result = db_cursor.fetchone()
db_cursor.close()
return (query_result,True)
except Exception as e:
logger.error('执行数据库查询操作失败:%s' % e)
db_cursor.close()
return(e,False)
def select_many_record(self, query, data=""):
'''返回结果只包含多条记录'''
logger.info('query:%s data:%s' % (query, data))
try:
db_cursor = self.dbconn.cursor()
if data:
db_cursor.execute(query, data)
else:
db_cursor.execute(query)
query_result = db_cursor.fetchall()
db_cursor.close()
return query_result
except Exception as e:
logger.error('执行数据库查询操作失败:%s' % e)
db_cursor.close()
exit()
def close(self):
self.dbconn.close | 0.206414 | 0.058185 |
"""CLI - Utilities."""
from __future__ import absolute_import, print_function, unicode_literals
import json
import platform
from contextlib import contextmanager
import click
import six
from click_spinner import spinner
from ..core.api.version import get_version as get_api_version
from ..core.version import get_version as get_cli_version
from .table import make_table
def make_user_agent(prefix=None):
"""Get a suitable user agent for identifying the CLI process."""
prefix = (prefix or platform.platform(terse=1)).strip().lower()
return "cloudsmith-cli/%(prefix)s cli:%(version)s api:%(api_version)s" % {
"version": get_cli_version(),
"api_version": get_api_version(),
"prefix": prefix,
}
def pretty_print_list_info(num_results, page_info=None, suffix=None):
"""Pretty print list info, with pagination, for user display."""
num_results_fg = "green" if num_results else "red"
num_results_text = click.style(str(num_results), fg=num_results_fg)
if page_info and page_info.is_valid:
page_range = page_info.calculate_range(num_results)
page_info_text = "page: %(page)s/%(page_total)s, page size: %(page_size)s" % {
"page": click.style(str(page_info.page), bold=True),
"page_size": click.style(str(page_info.page_size), bold=True),
"page_total": click.style(str(page_info.page_total), bold=True),
}
range_results_text = "%(from)s-%(to)s (%(num_results)s) of %(total)s" % {
"num_results": num_results_text,
"from": click.style(str(page_range[0]), fg=num_results_fg),
"to": click.style(str(page_range[1]), fg=num_results_fg),
"total": click.style(str(page_info.count), fg=num_results_fg),
}
else:
page_info_text = ""
range_results_text = num_results_text
click.secho(
"Results: %(range_results)s %(suffix)s%(page_info)s"
% {
"range_results": range_results_text,
"page_info": " (%s)" % page_info_text if page_info_text else "",
"suffix": suffix or "item(s)",
}
)
def pretty_print_table(headers, rows, title=None):
"""Pretty print a table from headers and rows."""
table = make_table(headers=headers, rows=rows)
def pretty_print_row(styled, plain):
"""Pretty print a row."""
click.secho(
" | ".join(
v + " " * (table.column_widths[k] - len(plain[k]))
for k, v in enumerate(styled)
)
)
if title:
click.secho(title, fg="white", bold=True)
click.secho("-" * 80, fg="yellow")
pretty_print_row(table.headers, table.plain_headers)
for k, row in enumerate(table.rows):
pretty_print_row(row, table.plain_rows[k])
def print_rate_limit_info(opts, rate_info):
"""Tell the user when we're being rate limited."""
if not rate_info:
return
show_info = (
opts.always_show_rate_limit or rate_info.interval > opts.rate_limit_warning
)
if not show_info:
return
click.echo(err=True)
click.secho(
"Throttling (rate limited) for: %(throttle)s seconds ... "
% {"throttle": click.style(six.text_type(rate_info.interval), reverse=True)},
err=True,
reset=False,
)
def maybe_print_as_json(opts, data, page_info=None):
"""Maybe print data as JSON."""
if opts.output not in ("json", "pretty_json"):
return False
# Attempt to convert the data to dicts (usually from API objects)
try:
data = data.to_dict()
except AttributeError:
pass
if isinstance(data, list):
for k, item in enumerate(data):
try:
data[k] = item.to_dict()
except AttributeError:
pass
root = {"data": data}
if page_info is not None and page_info.is_valid:
meta = root["meta"] = {}
meta["pagination"] = page_info.as_dict(num_results=len(data))
try:
if opts.output == "pretty_json":
dump = json.dumps(root, indent=4, sort_keys=True)
else:
dump = json.dumps(root, sort_keys=True)
except (TypeError, ValueError) as e:
click.secho(
"Failed to convert to JSON: %(err)s" % {"err": str(e)}, fg="red", err=True
)
return True
click.echo(dump)
return True
def confirm_operation(prompt, prefix=None, assume_yes=False, err=False):
"""Prompt the user for confirmation for dangerous actions."""
if assume_yes:
return True
prefix = prefix or click.style(
"Are you %s certain you want to" % (click.style("absolutely", bold=True))
)
prompt = "%(prefix)s %(prompt)s?" % {"prefix": prefix, "prompt": prompt}
if click.confirm(prompt, err=err):
return True
click.echo(err=err)
click.secho("OK, phew! Close call. :-)", fg="green", err=err)
return False
@contextmanager
def maybe_spinner(opts):
"""Only activate the spinner if not in debug mode."""
if opts.debug:
# No spinner
yield
else:
with spinner() as spin:
yield spin | cloudsmith_cli/cli/utils.py | """CLI - Utilities."""
from __future__ import absolute_import, print_function, unicode_literals
import json
import platform
from contextlib import contextmanager
import click
import six
from click_spinner import spinner
from ..core.api.version import get_version as get_api_version
from ..core.version import get_version as get_cli_version
from .table import make_table
def make_user_agent(prefix=None):
"""Get a suitable user agent for identifying the CLI process."""
prefix = (prefix or platform.platform(terse=1)).strip().lower()
return "cloudsmith-cli/%(prefix)s cli:%(version)s api:%(api_version)s" % {
"version": get_cli_version(),
"api_version": get_api_version(),
"prefix": prefix,
}
def pretty_print_list_info(num_results, page_info=None, suffix=None):
"""Pretty print list info, with pagination, for user display."""
num_results_fg = "green" if num_results else "red"
num_results_text = click.style(str(num_results), fg=num_results_fg)
if page_info and page_info.is_valid:
page_range = page_info.calculate_range(num_results)
page_info_text = "page: %(page)s/%(page_total)s, page size: %(page_size)s" % {
"page": click.style(str(page_info.page), bold=True),
"page_size": click.style(str(page_info.page_size), bold=True),
"page_total": click.style(str(page_info.page_total), bold=True),
}
range_results_text = "%(from)s-%(to)s (%(num_results)s) of %(total)s" % {
"num_results": num_results_text,
"from": click.style(str(page_range[0]), fg=num_results_fg),
"to": click.style(str(page_range[1]), fg=num_results_fg),
"total": click.style(str(page_info.count), fg=num_results_fg),
}
else:
page_info_text = ""
range_results_text = num_results_text
click.secho(
"Results: %(range_results)s %(suffix)s%(page_info)s"
% {
"range_results": range_results_text,
"page_info": " (%s)" % page_info_text if page_info_text else "",
"suffix": suffix or "item(s)",
}
)
def pretty_print_table(headers, rows, title=None):
"""Pretty print a table from headers and rows."""
table = make_table(headers=headers, rows=rows)
def pretty_print_row(styled, plain):
"""Pretty print a row."""
click.secho(
" | ".join(
v + " " * (table.column_widths[k] - len(plain[k]))
for k, v in enumerate(styled)
)
)
if title:
click.secho(title, fg="white", bold=True)
click.secho("-" * 80, fg="yellow")
pretty_print_row(table.headers, table.plain_headers)
for k, row in enumerate(table.rows):
pretty_print_row(row, table.plain_rows[k])
def print_rate_limit_info(opts, rate_info):
"""Tell the user when we're being rate limited."""
if not rate_info:
return
show_info = (
opts.always_show_rate_limit or rate_info.interval > opts.rate_limit_warning
)
if not show_info:
return
click.echo(err=True)
click.secho(
"Throttling (rate limited) for: %(throttle)s seconds ... "
% {"throttle": click.style(six.text_type(rate_info.interval), reverse=True)},
err=True,
reset=False,
)
def maybe_print_as_json(opts, data, page_info=None):
"""Maybe print data as JSON."""
if opts.output not in ("json", "pretty_json"):
return False
# Attempt to convert the data to dicts (usually from API objects)
try:
data = data.to_dict()
except AttributeError:
pass
if isinstance(data, list):
for k, item in enumerate(data):
try:
data[k] = item.to_dict()
except AttributeError:
pass
root = {"data": data}
if page_info is not None and page_info.is_valid:
meta = root["meta"] = {}
meta["pagination"] = page_info.as_dict(num_results=len(data))
try:
if opts.output == "pretty_json":
dump = json.dumps(root, indent=4, sort_keys=True)
else:
dump = json.dumps(root, sort_keys=True)
except (TypeError, ValueError) as e:
click.secho(
"Failed to convert to JSON: %(err)s" % {"err": str(e)}, fg="red", err=True
)
return True
click.echo(dump)
return True
def confirm_operation(prompt, prefix=None, assume_yes=False, err=False):
"""Prompt the user for confirmation for dangerous actions."""
if assume_yes:
return True
prefix = prefix or click.style(
"Are you %s certain you want to" % (click.style("absolutely", bold=True))
)
prompt = "%(prefix)s %(prompt)s?" % {"prefix": prefix, "prompt": prompt}
if click.confirm(prompt, err=err):
return True
click.echo(err=err)
click.secho("OK, phew! Close call. :-)", fg="green", err=err)
return False
@contextmanager
def maybe_spinner(opts):
"""Only activate the spinner if not in debug mode."""
if opts.debug:
# No spinner
yield
else:
with spinner() as spin:
yield spin | 0.696062 | 0.167797 |
import os
import datetime
import traceback
import asyncio
import asyncpg
import sys
try:
import uvloop
except ImportError:
if sys.platform == "win32":
pass
elif sys.platform == "linux":
print(
"""UvLoop is not installed. Please install it with "pip install uvloop".
""")
else:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
import discord
from discord.ext import commands
"""
This is a bot made by ir3#3333.
"""
class Zane(commands.AutoShardedBot):
def __init__(self):
self.bot_cogs = [
'jishaku',
'cogs.image',
'cogs.information',
'cogs.eh',
'cogs.moderation',
'cogs.dbots'
]
self.prefixes = [
'za.',
'zane '
]
self.color = discord.Color.blue().value
self.accept_commands = False
self.init_time = datetime.datetime.utcnow()
self.owner_ids = [217462890364403712, 455289384187592704]
super().__init__(command_prefix=self.prefix)
self.loop.create_task(self.__ainit__())
async def __ainit__(self):
db = await asyncpg.create_pool(
user=os.environ['USER'],
password=os.environ['PASSWORD'],
database=os.environ['DATABASE'],
host=os.environ['HOST']
)
print("DB: Connected")
with open("setup.sql") as f:
await db.execute(f.read())
print("DB: Setup.sql executed.")
self.db = db
@property
def loading_emoji(self):
return self.get_emoji(514917324709429344)
async def prefix(self, bot, message):
return commands.when_mentioned_or(*self.prefixes)(bot, message)
async def on_message(self, message):
if self.accept_commands:
await self.process_commands(message)
def run(self, token: str):
for cog in self.bot_cogs:
try:
self.load_extension(cog)
print(f"Loaded: {cog}")
except Exception:
print(f"Error Loading {cog}: Traceback printed below.")
traceback.print_exc()
super().run(token)
async def set_status(self):
await self.change_presence(
status=discord.Status.online,
activity=discord.Activity(
type=discord.ActivityType.watching,
name=f"over {len(list(self.get_all_members()))} users | {self.prefixes[0]}help"
)
)
async def on_ready(self):
print(f"""Bot Started:
ID: {self.user.id}
Username: {self.user.name}
Discriminator: {self.user.discriminator}
Guild Count: {len(self.guilds)}
User Count: {len(self.users)}""")
self.loop.create_task(self.set_status())
self.app_info = await self.application_info()
self.accept_commands = True
async def is_owner(self, user):
if user.id in self.owner_ids:
return True
return False
if __name__ == "__main__":
Zane().run(os.environ['TOKEN']) | Zane/main.py | import os
import datetime
import traceback
import asyncio
import asyncpg
import sys
try:
import uvloop
except ImportError:
if sys.platform == "win32":
pass
elif sys.platform == "linux":
print(
"""UvLoop is not installed. Please install it with "pip install uvloop".
""")
else:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
import discord
from discord.ext import commands
"""
This is a bot made by ir3#3333.
"""
class Zane(commands.AutoShardedBot):
def __init__(self):
self.bot_cogs = [
'jishaku',
'cogs.image',
'cogs.information',
'cogs.eh',
'cogs.moderation',
'cogs.dbots'
]
self.prefixes = [
'za.',
'zane '
]
self.color = discord.Color.blue().value
self.accept_commands = False
self.init_time = datetime.datetime.utcnow()
self.owner_ids = [217462890364403712, 455289384187592704]
super().__init__(command_prefix=self.prefix)
self.loop.create_task(self.__ainit__())
async def __ainit__(self):
db = await asyncpg.create_pool(
user=os.environ['USER'],
password=os.environ['PASSWORD'],
database=os.environ['DATABASE'],
host=os.environ['HOST']
)
print("DB: Connected")
with open("setup.sql") as f:
await db.execute(f.read())
print("DB: Setup.sql executed.")
self.db = db
@property
def loading_emoji(self):
return self.get_emoji(514917324709429344)
async def prefix(self, bot, message):
return commands.when_mentioned_or(*self.prefixes)(bot, message)
async def on_message(self, message):
if self.accept_commands:
await self.process_commands(message)
def run(self, token: str):
for cog in self.bot_cogs:
try:
self.load_extension(cog)
print(f"Loaded: {cog}")
except Exception:
print(f"Error Loading {cog}: Traceback printed below.")
traceback.print_exc()
super().run(token)
async def set_status(self):
await self.change_presence(
status=discord.Status.online,
activity=discord.Activity(
type=discord.ActivityType.watching,
name=f"over {len(list(self.get_all_members()))} users | {self.prefixes[0]}help"
)
)
async def on_ready(self):
print(f"""Bot Started:
ID: {self.user.id}
Username: {self.user.name}
Discriminator: {self.user.discriminator}
Guild Count: {len(self.guilds)}
User Count: {len(self.users)}""")
self.loop.create_task(self.set_status())
self.app_info = await self.application_info()
self.accept_commands = True
async def is_owner(self, user):
if user.id in self.owner_ids:
return True
return False
if __name__ == "__main__":
Zane().run(os.environ['TOKEN']) | 0.280025 | 0.078784 |
from users_model import User, Init
from . import api
from flask import request, jsonify
import ConfigParser
from botasky.utils.MyCONN import MySQL
from botasky.utils.MyFILE import project_abdir, recursiveSearchFile
from botasky.utils.MyLOG import MyLog
logConfig = recursiveSearchFile(project_abdir, '*logConfig.ini')[0]
mylog = MyLog(logConfig, 'register_verify_user.py')
logger = mylog.outputLog()
__all__ = ['register_user', 'verify_user']
__author__ = 'zhihao'
@api.route('/register', methods=['GET', 'POST'])
def register_user():
'''API users register'''
username = request.args.get('username', type=str, default=None)
password = request.args.get('password', type=str, default=None)
config = ConfigParser.ConfigParser()
metaConfig = recursiveSearchFile(project_abdir, '*metaConfig.ini')[0]
config.read(metaConfig)
engine = Init.Engine(config.get('META', 'user'), config.get('META', 'pwd'),
config.get('META', 'host'), config.get('META', 'port'),
config.get('META', 'db'))
session = Init.Session(engine)
try:
Init.Insert_User(session, username, password)
exec_info = "[action]:register user" \
"[status]:OK" \
"[username]:{username}".format(username=username)
logger.info(exec_info)
except Exception, e:
error_msg = "[action]:register user" \
"[status]:FAIL" \
"[username]:{username}" \
"[Errorcode]:{e}".format(username=username, e=e)
logger.error(error_msg)
return jsonify({'status': '[FAIL]',
'msg': 'register fail, may be repeated because of username or password',
'data': {'username': username, 'password': password}})
return jsonify({'status': '[OK]',
'msg': 'register OK',
'data': {'username': username, 'password': password}})
from flask_httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()
@auth.verify_password
def verify_user(username, password):
'''API users verify decorator'''
config = ConfigParser.ConfigParser()
metaConfig = recursiveSearchFile(project_abdir, '*metaConfig.ini')[0]
config.read(metaConfig)
dbconfig = {'host': config.get('META', 'host'),
'port': int(config.get('META', 'port')),
'user': config.get('META', 'user'),
'passwd': config.get('META', 'pwd'),
'db': config.get('META', 'db'),
'charset': 'utf8'}
db = MySQL(dbconfig)
sql = "select id,name,password_hash from users where name = '{username}'".format(username=username)
db.query(sql)
info = db.fetchOneRow()
db.close()
check_user = User(id=info[0], name=info[1], password_hash=info[2])
if not check_user or not check_user.verify_password(password):
error_msg = "[action]:verify user" \
"[status]:FAIL" \
"[username]:{username}" \
"[verify status]:{status}".format(username=check_user.name,
status=check_user.verify_password(password))
logger.error(error_msg)
return False
exec_info = "[action]:verify user" \
"[status]:OK" \
"[username]:{username}".format(username=username)
logger.info(exec_info)
return True
'''
@auth.verify_password
def verify_user(username, password):
#API users verify decorator
config = ConfigParser.ConfigParser()
metaConfig = recursiveSearchFile(project_abdir, '*metaConfig.ini')[0]
config.read(metaConfig)
engine = Init.Engine(config.get('META', 'user'), config.get('META', 'pwd'),
config.get('META', 'host'), config.get('META', 'port'),
config.get('META', 'db'))
session = Init.Session(engine)
info = session.execute("select id,name,password_hash from users where name = '{username}'".format(username=username)).first()
session.close()
check_user = User(id=info[0], name=info[1], password_hash=info[2])
if not check_user or not check_user.verify_password(password):
error_msg = "[action]:verify user" \
"[status]:FAIL" \
"[username]:{username}" \
"[verify status]:{status}".format(username=check_user.name,
status=check_user.verify_password(password))
logger.error(error_msg)
return False
exec_info = "[action]:verify user" \
"[status]:OK" \
"[username]:{username}".format(username=username)
logger.info(exec_info)
return True
'''
@api.route('/resource')
@auth.login_required
def get_resource():
'''verify example'''
return jsonify({'data': 'Hello'})
"""
@api.route('/verify', methods=['GET', 'POST'])
def verify_user():
'''API users verify'''
username = request.args.get('username', type=str, default=None)
password = request.args.get('password', type=str, default=None)
engine = Init.Engine('admin', 'tfkj705', '192.168.41.40', 3306, 'zhihao_test')
session = Init.Session(engine)
info = session.execute("select * from users where name = '{username}'".format(username=username)).first()
check_user = User(id=info[0], name=info[1], password_hash=info[2])
verify_status = check_user.verify_password(password)
return jsonify({'username': username, 'password': password, 'verify_status': verify_status})
""" | botasky/api_0_1/register_verify_user.py | from users_model import User, Init
from . import api
from flask import request, jsonify
import ConfigParser
from botasky.utils.MyCONN import MySQL
from botasky.utils.MyFILE import project_abdir, recursiveSearchFile
from botasky.utils.MyLOG import MyLog
logConfig = recursiveSearchFile(project_abdir, '*logConfig.ini')[0]
mylog = MyLog(logConfig, 'register_verify_user.py')
logger = mylog.outputLog()
__all__ = ['register_user', 'verify_user']
__author__ = 'zhihao'
@api.route('/register', methods=['GET', 'POST'])
def register_user():
'''API users register'''
username = request.args.get('username', type=str, default=None)
password = request.args.get('password', type=str, default=None)
config = ConfigParser.ConfigParser()
metaConfig = recursiveSearchFile(project_abdir, '*metaConfig.ini')[0]
config.read(metaConfig)
engine = Init.Engine(config.get('META', 'user'), config.get('META', 'pwd'),
config.get('META', 'host'), config.get('META', 'port'),
config.get('META', 'db'))
session = Init.Session(engine)
try:
Init.Insert_User(session, username, password)
exec_info = "[action]:register user" \
"[status]:OK" \
"[username]:{username}".format(username=username)
logger.info(exec_info)
except Exception, e:
error_msg = "[action]:register user" \
"[status]:FAIL" \
"[username]:{username}" \
"[Errorcode]:{e}".format(username=username, e=e)
logger.error(error_msg)
return jsonify({'status': '[FAIL]',
'msg': 'register fail, may be repeated because of username or password',
'data': {'username': username, 'password': password}})
return jsonify({'status': '[OK]',
'msg': 'register OK',
'data': {'username': username, 'password': password}})
from flask_httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()
@auth.verify_password
def verify_user(username, password):
'''API users verify decorator'''
config = ConfigParser.ConfigParser()
metaConfig = recursiveSearchFile(project_abdir, '*metaConfig.ini')[0]
config.read(metaConfig)
dbconfig = {'host': config.get('META', 'host'),
'port': int(config.get('META', 'port')),
'user': config.get('META', 'user'),
'passwd': config.get('META', 'pwd'),
'db': config.get('META', 'db'),
'charset': 'utf8'}
db = MySQL(dbconfig)
sql = "select id,name,password_hash from users where name = '{username}'".format(username=username)
db.query(sql)
info = db.fetchOneRow()
db.close()
check_user = User(id=info[0], name=info[1], password_hash=info[2])
if not check_user or not check_user.verify_password(password):
error_msg = "[action]:verify user" \
"[status]:FAIL" \
"[username]:{username}" \
"[verify status]:{status}".format(username=check_user.name,
status=check_user.verify_password(password))
logger.error(error_msg)
return False
exec_info = "[action]:verify user" \
"[status]:OK" \
"[username]:{username}".format(username=username)
logger.info(exec_info)
return True
'''
@auth.verify_password
def verify_user(username, password):
#API users verify decorator
config = ConfigParser.ConfigParser()
metaConfig = recursiveSearchFile(project_abdir, '*metaConfig.ini')[0]
config.read(metaConfig)
engine = Init.Engine(config.get('META', 'user'), config.get('META', 'pwd'),
config.get('META', 'host'), config.get('META', 'port'),
config.get('META', 'db'))
session = Init.Session(engine)
info = session.execute("select id,name,password_hash from users where name = '{username}'".format(username=username)).first()
session.close()
check_user = User(id=info[0], name=info[1], password_hash=info[2])
if not check_user or not check_user.verify_password(password):
error_msg = "[action]:verify user" \
"[status]:FAIL" \
"[username]:{username}" \
"[verify status]:{status}".format(username=check_user.name,
status=check_user.verify_password(password))
logger.error(error_msg)
return False
exec_info = "[action]:verify user" \
"[status]:OK" \
"[username]:{username}".format(username=username)
logger.info(exec_info)
return True
'''
@api.route('/resource')
@auth.login_required
def get_resource():
'''verify example'''
return jsonify({'data': 'Hello'})
"""
@api.route('/verify', methods=['GET', 'POST'])
def verify_user():
'''API users verify'''
username = request.args.get('username', type=str, default=None)
password = request.args.get('password', type=str, default=None)
engine = Init.Engine('admin', 'tfkj705', '192.168.41.40', 3306, 'zhihao_test')
session = Init.Session(engine)
info = session.execute("select * from users where name = '{username}'".format(username=username)).first()
check_user = User(id=info[0], name=info[1], password_hash=info[2])
verify_status = check_user.verify_password(password)
return jsonify({'username': username, 'password': password, 'verify_status': verify_status})
""" | 0.287268 | 0.046184 |
import GeodisTK
import numpy as np
import time
from PIL import Image
import matplotlib.pyplot as plt
def geodesic_distance_2d(I, S, lamb, iter):
'''
get 2d geodesic disntance by raser scanning.
I: input image, can have multiple channels. Type should be np.float32.
S: binary image where non-zero pixels are used as seeds. Type should be np.uint8.
lamb: weighting betwween 0.0 and 1.0
if lamb==0.0, return spatial euclidean distance without considering gradient
if lamb==1.0, the distance is based on gradient only without using spatial distance
iter: number of iteration for raster scanning.
'''
return GeodisTK.geodesic2d_raster_scan(I, S, lamb, iter)
def demo_geodesic_distance2d(img, seed_pos):
I = np.asanyarray(img, np.float32)
S = np.zeros((I.shape[0], I.shape[1]), np.uint8)
S[seed_pos[0]][seed_pos[1]] = 1
t0 = time.time()
D1 = GeodisTK.geodesic2d_fast_marching(I,S)
t1 = time.time()
D2 = geodesic_distance_2d(I, S, 1.0, 2)
dt1 = t1 - t0
dt2 = time.time() - t1
D3 = geodesic_distance_2d(I, S, 0.0, 2)
D4 = geodesic_distance_2d(I, S, 0.5, 2)
print("runtime(s) of fast marching {0:}".format(dt1))
print("runtime(s) of raster scan {0:}".format(dt2))
plt.figure(figsize=(15,5))
plt.subplot(1,5,1); plt.imshow(img)
plt.autoscale(False); plt.plot([seed_pos[0]], [seed_pos[1]], 'ro')
plt.axis('off'); plt.title('(a) input image \n with a seed point')
plt.subplot(1,5,2); plt.imshow(D1)
plt.axis('off'); plt.title('(b) Geodesic distance \n based on fast marching')
plt.subplot(1,5,3); plt.imshow(D2)
plt.axis('off'); plt.title('(c) Geodesic distance \n based on ranster scan')
plt.subplot(1,5,4); plt.imshow(D3)
plt.axis('off'); plt.title('(d) Euclidean distance')
plt.subplot(1,5,5); plt.imshow(D4)
plt.axis('off'); plt.title('(e) Mexture of Geodesic \n and Euclidean distance')
plt.show()
def demo_geodesic_distance2d_gray_scale_image():
img = Image.open('data/img2d.png').convert('L')
seed_position = [100, 100]
demo_geodesic_distance2d(img, seed_position)
def demo_geodesic_distance2d_RGB_image():
img = Image.open('data/ISIC_546.jpg')
seed_position = [128, 128]
demo_geodesic_distance2d(img, seed_position)
if __name__ == '__main__':
print("example list")
print(" 0 -- example for gray scale image")
print(" 1 -- example for RB image")
print("please enter the index of an example:")
method = input()
method = '{0:}'.format(method)
if(method == '0'):
demo_geodesic_distance2d_gray_scale_image()
elif(method == '1'):
demo_geodesic_distance2d_RGB_image()
else:
print("invalid number : {0:}".format(method)) | demo2d.py | import GeodisTK
import numpy as np
import time
from PIL import Image
import matplotlib.pyplot as plt
def geodesic_distance_2d(I, S, lamb, iter):
'''
get 2d geodesic disntance by raser scanning.
I: input image, can have multiple channels. Type should be np.float32.
S: binary image where non-zero pixels are used as seeds. Type should be np.uint8.
lamb: weighting betwween 0.0 and 1.0
if lamb==0.0, return spatial euclidean distance without considering gradient
if lamb==1.0, the distance is based on gradient only without using spatial distance
iter: number of iteration for raster scanning.
'''
return GeodisTK.geodesic2d_raster_scan(I, S, lamb, iter)
def demo_geodesic_distance2d(img, seed_pos):
I = np.asanyarray(img, np.float32)
S = np.zeros((I.shape[0], I.shape[1]), np.uint8)
S[seed_pos[0]][seed_pos[1]] = 1
t0 = time.time()
D1 = GeodisTK.geodesic2d_fast_marching(I,S)
t1 = time.time()
D2 = geodesic_distance_2d(I, S, 1.0, 2)
dt1 = t1 - t0
dt2 = time.time() - t1
D3 = geodesic_distance_2d(I, S, 0.0, 2)
D4 = geodesic_distance_2d(I, S, 0.5, 2)
print("runtime(s) of fast marching {0:}".format(dt1))
print("runtime(s) of raster scan {0:}".format(dt2))
plt.figure(figsize=(15,5))
plt.subplot(1,5,1); plt.imshow(img)
plt.autoscale(False); plt.plot([seed_pos[0]], [seed_pos[1]], 'ro')
plt.axis('off'); plt.title('(a) input image \n with a seed point')
plt.subplot(1,5,2); plt.imshow(D1)
plt.axis('off'); plt.title('(b) Geodesic distance \n based on fast marching')
plt.subplot(1,5,3); plt.imshow(D2)
plt.axis('off'); plt.title('(c) Geodesic distance \n based on ranster scan')
plt.subplot(1,5,4); plt.imshow(D3)
plt.axis('off'); plt.title('(d) Euclidean distance')
plt.subplot(1,5,5); plt.imshow(D4)
plt.axis('off'); plt.title('(e) Mexture of Geodesic \n and Euclidean distance')
plt.show()
def demo_geodesic_distance2d_gray_scale_image():
img = Image.open('data/img2d.png').convert('L')
seed_position = [100, 100]
demo_geodesic_distance2d(img, seed_position)
def demo_geodesic_distance2d_RGB_image():
img = Image.open('data/ISIC_546.jpg')
seed_position = [128, 128]
demo_geodesic_distance2d(img, seed_position)
if __name__ == '__main__':
print("example list")
print(" 0 -- example for gray scale image")
print(" 1 -- example for RB image")
print("please enter the index of an example:")
method = input()
method = '{0:}'.format(method)
if(method == '0'):
demo_geodesic_distance2d_gray_scale_image()
elif(method == '1'):
demo_geodesic_distance2d_RGB_image()
else:
print("invalid number : {0:}".format(method)) | 0.481698 | 0.678331 |
import datetime
import hashlib
import textwrap
import uuid
import itertools
import json
import logging
import pathlib
import pprintpp
import time
from typing import Any
from typing import Dict
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Optional
from typing import Tuple
import msgpack
import requests
import sqlalchemy as sa
import tqdm
from requests import HTTPError
from typer import Argument
from typer import Context as TyperContext
from typer import Option
from typer import Exit
from typer import echo
from spinta import exceptions
from spinta import spyna
from spinta.cli.helpers.auth import require_auth
from spinta.cli.helpers.data import ModelRow
from spinta.cli.helpers.data import count_rows
from spinta.cli.helpers.data import ensure_data_dir
from spinta.cli.helpers.data import iter_model_rows
from spinta.cli.helpers.store import prepare_manifest
from spinta.client import RemoteClientCredentials
from spinta.client import get_access_token
from spinta.client import get_client_credentials
from spinta.components import Action
from spinta.components import Config
from spinta.components import Context
from spinta.components import Mode
from spinta.components import Model
from spinta.core.context import configure_context
from spinta.types.namespace import sort_models_by_refs
from spinta.utils.data import take
from spinta.utils.json import fix_data_for_json
from spinta.utils.nestedstruct import flatten
from spinta.utils.units import tobytes
from spinta.utils.units import toseconds
log = logging.getLogger(__name__)
def push(
ctx: TyperContext,
manifests: Optional[List[str]] = Argument(None, help=(
"Source manifest files to copy from"
)),
output: Optional[str] = Option(None, '-o', '--output', help=(
"Output data to a given location, by default outputs to stdout"
)),
credentials: str = Option(None, '--credentials', help=(
"Credentials file, defaults to {config_path}/credentials.cfg"
)),
dataset: str = Option(None, '-d', '--dataset', help=(
"Push only specified dataset"
)),
auth: str = Option(None, '-a', '--auth', help=(
"Authorize as a client, defaults to {default_auth_client}"
)),
limit: int = Option(None, help=(
"Limit number of rows read from each model"
)),
chunk_size: str = Option('1m', help=(
"Push data in chunks (1b, 1k, 2m, ...), default: 1m"
)),
stop_time: str = Option(None, help=(
"Stop pushing after given time (1s, 1m, 2h, ...), by default does not "
"stops until all data is pushed"
)),
stop_row: int = Option(None, help=(
"Stop after pushing n rows, by default does not stop until all data "
"is pushed"
)),
state: pathlib.Path = Option(None, help=(
"Save push state into a file, by default state is saved to "
"{data_path}/push/{remote}.db SQLite database file"
)),
mode: Mode = Option('external', help=(
"Mode of backend operation, default: external"
)),
dry_run: bool = Option(False, '--dry-run', help=(
"Read data to be pushed, but do not push or write data to the "
"destination."
)),
stop_on_error: bool = Option(False, '--stop-on-error', help=(
"Exit immediately on first error."
))
):
"""Push data to external data store"""
if chunk_size:
chunk_size = tobytes(chunk_size)
if stop_time:
stop_time = toseconds(stop_time)
context = configure_context(ctx.obj, manifests, mode=mode)
store = prepare_manifest(context)
config: Config = context.get('config')
if credentials:
credsfile = pathlib.Path(credentials)
if not credsfile.exists():
echo(f"Credentials file {credsfile} does not exit.")
raise Exit(code=1)
else:
credsfile = config.credentials_file
# TODO: Read client credentials only if a Spinta URL is given.
creds = get_client_credentials(credsfile, output)
if not state:
ensure_data_dir(config.data_path / 'push')
state = config.data_path / 'push' / f'{creds.remote}.db'
manifest = store.manifest
if dataset and dataset not in manifest.datasets:
echo(str(exceptions.NodeNotFound(manifest, type='dataset', name=dataset)))
raise Exit(code=1)
ns = manifest.namespaces['']
with context:
client = auth or config.default_auth_client
require_auth(context, client)
context.attach('transaction', manifest.backend.transaction)
backends = set()
for backend in store.backends.values():
backends.add(backend.name)
context.attach(f'transaction.{backend.name}', backend.begin)
for backend in manifest.backends.values():
backends.add(backend.name)
context.attach(f'transaction.{backend.name}', backend.begin)
for dataset_ in manifest.datasets.values():
for resource in dataset_.resources.values():
if resource.backend and resource.backend.name not in backends:
backends.add(resource.backend.name)
context.attach(f'transaction.{resource.backend.name}', resource.backend.begin)
for keymap in store.keymaps.values():
context.attach(f'keymap.{keymap.name}', lambda: keymap)
from spinta.types.namespace import traverse_ns_models
models = traverse_ns_models(context, ns, Action.SEARCH, dataset)
models = sort_models_by_refs(models)
models = list(reversed(list(models)))
counts = count_rows(
context,
models,
limit,
stop_on_error=stop_on_error,
)
if state:
engine, metadata = _init_push_state(state, models)
context.attach('push.state.conn', engine.begin)
rows = iter_model_rows(
context,
models,
counts,
limit,
stop_on_error=stop_on_error,
)
rows = _prepare_rows_for_push(rows)
rows = tqdm.tqdm(rows, 'PUSH', ascii=True, total=sum(counts.values()))
if stop_time:
rows = _add_stop_time(rows, stop_time)
if state:
rows = _check_push_state(context, rows, metadata)
if stop_row:
rows = itertools.islice(rows, stop_row)
rows = _push_to_remote_spinta(rows, creds, chunk_size, dry_run=dry_run)
if state and not dry_run:
rows = _save_push_state(context, rows, metadata)
while True:
try:
next(rows)
except StopIteration:
break
except:
if stop_on_error:
raise
log.exception("Error while reading data.")
class _PushRow:
model: Model
data: Dict[str, Any]
rev: Optional[str]
saved: bool = False
def __init__(self, model: Model, data: Dict[str, Any]):
self.model = model
self.data = data
self.rev = None
self.saved = False
def _prepare_rows_for_push(rows: Iterable[ModelRow]) -> Iterator[_PushRow]:
for model, row in rows:
_id = row['_id']
_type = row['_type']
where = {
'name': 'eq',
'args': [
{'name': 'bind', 'args': ['_id']},
_id,
]
}
payload = {
'_op': 'upsert',
'_type': _type,
'_id': _id,
'_where': spyna.unparse(where),
**{k: v for k, v in row.items() if not k.startswith('_')}
}
yield _PushRow(model, payload)
def _push_to_remote_spinta(
rows: Iterable[_PushRow],
creds: RemoteClientCredentials,
chunk_size: int,
*,
dry_run: bool = False,
stop_on_error: bool = False,
) -> Iterator[_PushRow]:
echo(f"Get access token from {creds.server}")
token = get_access_token(creds)
session = requests.Session()
session.headers['Content-Type'] = 'application/json'
session.headers['Authorization'] = f'Bearer {token}'
prefix = '{"_data":['
suffix = ']}'
slen = len(suffix)
chunk = prefix
ready = []
for row in rows:
data = fix_data_for_json(row.data)
data = json.dumps(data, ensure_ascii=False)
if ready and len(chunk) + len(data) + slen > chunk_size:
yield from _send_and_receive(
session,
creds.server,
ready,
chunk + suffix,
dry_run=dry_run,
stop_on_error=stop_on_error,
)
chunk = prefix
ready = []
chunk += (',' if ready else '') + data
ready.append(row)
if ready:
yield from _send_and_receive(
session,
creds.server,
ready,
chunk + suffix,
dry_run=dry_run,
stop_on_error=stop_on_error,
)
def _get_row_for_error(rows: List[_PushRow]) -> str:
size = len(rows)
if size > 0:
row = rows[0]
data = pprintpp.pformat(row.data)
return (
f" Model {row.model.name},"
f" items in chunk: {size},"
f" first item in chunk:\n {data}"
)
else:
return ''
def _send_and_receive(
session: requests.Session,
target: str,
rows: List[_PushRow],
data: str,
*,
dry_run: bool = False,
stop_on_error: bool = False,
) -> Iterator[_PushRow]:
if dry_run:
recv = _send_data_dry_run(data)
else:
recv = _send_data(
session,
target,
rows,
data,
stop_on_error=stop_on_error,
)
yield from _map_sent_and_recv(rows, recv)
def _send_data_dry_run(
data: str,
) -> Optional[List[Dict[str, Any]]]:
"""Pretend data has been sent to a target location."""
recv = json.loads(data)['_data']
for row in recv:
if '_id' not in row:
row['_id'] = str(uuid.uuid4())
row['_rev'] = str(uuid.uuid4())
return recv
def _send_data(
session: requests.Session,
target: str,
rows: List[_PushRow],
data: str,
*,
stop_on_error: bool = False,
) -> Optional[List[Dict[str, Any]]]:
data = data.encode('utf-8')
try:
resp = session.post(target, data=data)
except IOError as e:
if stop_on_error:
raise
log.error(
(
"Error when sending and receiving data.%s\n"
"Error: %s"
),
_get_row_for_error(rows),
e,
)
return
try:
resp.raise_for_status()
except HTTPError:
if stop_on_error:
raise
log.error(
(
"Error when sending and receiving data.%s\n"
"Server response (status=%s):\n%s"
),
_get_row_for_error(rows),
resp.status_code,
textwrap.indent(pprintpp.pformat(resp.json()), ' '),
)
return
return resp.json()['_data']
def _map_sent_and_recv(
sent: List[_PushRow],
recv: List[Dict[str, Any]],
) -> Iterator[_PushRow]:
assert len(sent) == len(recv), (
f"len(sent) = {len(sent)}, len(received) = {len(recv)}"
)
for sent_row, recv_row in zip(sent, recv):
assert sent_row.data['_id'] == recv_row['_id'], (
f"sent._id = {sent_row.data['_id']}, "
f"received._id = {recv_row['_id']}"
)
yield sent_row
def _add_stop_time(rows, stop):
start = time.time()
for row in rows:
yield row
if time.time() - start > stop:
break
def _init_push_state(
file: pathlib.Path,
models: List[Model],
) -> Tuple[sa.engine.Engine, sa.MetaData]:
engine = sa.create_engine(f'sqlite:///{file}')
metadata = sa.MetaData(engine)
for model in models:
table = sa.Table(
model.name, metadata,
sa.Column('id', sa.Unicode, primary_key=True),
sa.Column('rev', sa.Unicode),
sa.Column('pushed', sa.DateTime),
)
table.create(checkfirst=True)
return engine, metadata
def _get_model_type(row: _PushRow) -> str:
return row.data['_type']
def _check_push_state(
context: Context,
rows: Iterable[_PushRow],
metadata: sa.MetaData,
):
conn = context.get('push.state.conn')
for model_type, group in itertools.groupby(rows, key=_get_model_type):
table = metadata.tables[model_type]
query = sa.select([table.c.id, table.c.rev])
saved = {
state[table.c.id]: state[table.c.rev]
for state in conn.execute(query)
}
for row in group:
_id = row.data['_id']
rev = fix_data_for_json(take(row.data))
rev = flatten([rev])
rev = [[k, v] for x in rev for k, v in sorted(x.items())]
rev = msgpack.dumps(rev, strict_types=True)
rev = hashlib.sha1(rev).hexdigest()
row.rev = rev
row.saved = _id in saved
if saved.get(_id) == row.rev:
continue # Nothing has changed.
yield row
def _save_push_state(
context: Context,
rows: Iterable[_PushRow],
metadata: sa.MetaData,
):
conn = context.get('push.state.conn')
for row in rows:
table = metadata.tables[row.data['_type']]
if row.saved:
conn.execute(
table.update().
where(table.c.id == row.data['_id']).
values(
id=row.data['_id'],
rev=row.rev,
pushed=datetime.datetime.now(),
)
)
else:
conn.execute(
table.insert().
values(
id=row.data['_id'],
rev=row.rev,
pushed=datetime.datetime.now(),
)
)
yield row | spinta/cli/push.py | import datetime
import hashlib
import textwrap
import uuid
import itertools
import json
import logging
import pathlib
import pprintpp
import time
from typing import Any
from typing import Dict
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Optional
from typing import Tuple
import msgpack
import requests
import sqlalchemy as sa
import tqdm
from requests import HTTPError
from typer import Argument
from typer import Context as TyperContext
from typer import Option
from typer import Exit
from typer import echo
from spinta import exceptions
from spinta import spyna
from spinta.cli.helpers.auth import require_auth
from spinta.cli.helpers.data import ModelRow
from spinta.cli.helpers.data import count_rows
from spinta.cli.helpers.data import ensure_data_dir
from spinta.cli.helpers.data import iter_model_rows
from spinta.cli.helpers.store import prepare_manifest
from spinta.client import RemoteClientCredentials
from spinta.client import get_access_token
from spinta.client import get_client_credentials
from spinta.components import Action
from spinta.components import Config
from spinta.components import Context
from spinta.components import Mode
from spinta.components import Model
from spinta.core.context import configure_context
from spinta.types.namespace import sort_models_by_refs
from spinta.utils.data import take
from spinta.utils.json import fix_data_for_json
from spinta.utils.nestedstruct import flatten
from spinta.utils.units import tobytes
from spinta.utils.units import toseconds
log = logging.getLogger(__name__)
def push(
ctx: TyperContext,
manifests: Optional[List[str]] = Argument(None, help=(
"Source manifest files to copy from"
)),
output: Optional[str] = Option(None, '-o', '--output', help=(
"Output data to a given location, by default outputs to stdout"
)),
credentials: str = Option(None, '--credentials', help=(
"Credentials file, defaults to {config_path}/credentials.cfg"
)),
dataset: str = Option(None, '-d', '--dataset', help=(
"Push only specified dataset"
)),
auth: str = Option(None, '-a', '--auth', help=(
"Authorize as a client, defaults to {default_auth_client}"
)),
limit: int = Option(None, help=(
"Limit number of rows read from each model"
)),
chunk_size: str = Option('1m', help=(
"Push data in chunks (1b, 1k, 2m, ...), default: 1m"
)),
stop_time: str = Option(None, help=(
"Stop pushing after given time (1s, 1m, 2h, ...), by default does not "
"stops until all data is pushed"
)),
stop_row: int = Option(None, help=(
"Stop after pushing n rows, by default does not stop until all data "
"is pushed"
)),
state: pathlib.Path = Option(None, help=(
"Save push state into a file, by default state is saved to "
"{data_path}/push/{remote}.db SQLite database file"
)),
mode: Mode = Option('external', help=(
"Mode of backend operation, default: external"
)),
dry_run: bool = Option(False, '--dry-run', help=(
"Read data to be pushed, but do not push or write data to the "
"destination."
)),
stop_on_error: bool = Option(False, '--stop-on-error', help=(
"Exit immediately on first error."
))
):
"""Push data to external data store"""
if chunk_size:
chunk_size = tobytes(chunk_size)
if stop_time:
stop_time = toseconds(stop_time)
context = configure_context(ctx.obj, manifests, mode=mode)
store = prepare_manifest(context)
config: Config = context.get('config')
if credentials:
credsfile = pathlib.Path(credentials)
if not credsfile.exists():
echo(f"Credentials file {credsfile} does not exit.")
raise Exit(code=1)
else:
credsfile = config.credentials_file
# TODO: Read client credentials only if a Spinta URL is given.
creds = get_client_credentials(credsfile, output)
if not state:
ensure_data_dir(config.data_path / 'push')
state = config.data_path / 'push' / f'{creds.remote}.db'
manifest = store.manifest
if dataset and dataset not in manifest.datasets:
echo(str(exceptions.NodeNotFound(manifest, type='dataset', name=dataset)))
raise Exit(code=1)
ns = manifest.namespaces['']
with context:
client = auth or config.default_auth_client
require_auth(context, client)
context.attach('transaction', manifest.backend.transaction)
backends = set()
for backend in store.backends.values():
backends.add(backend.name)
context.attach(f'transaction.{backend.name}', backend.begin)
for backend in manifest.backends.values():
backends.add(backend.name)
context.attach(f'transaction.{backend.name}', backend.begin)
for dataset_ in manifest.datasets.values():
for resource in dataset_.resources.values():
if resource.backend and resource.backend.name not in backends:
backends.add(resource.backend.name)
context.attach(f'transaction.{resource.backend.name}', resource.backend.begin)
for keymap in store.keymaps.values():
context.attach(f'keymap.{keymap.name}', lambda: keymap)
from spinta.types.namespace import traverse_ns_models
models = traverse_ns_models(context, ns, Action.SEARCH, dataset)
models = sort_models_by_refs(models)
models = list(reversed(list(models)))
counts = count_rows(
context,
models,
limit,
stop_on_error=stop_on_error,
)
if state:
engine, metadata = _init_push_state(state, models)
context.attach('push.state.conn', engine.begin)
rows = iter_model_rows(
context,
models,
counts,
limit,
stop_on_error=stop_on_error,
)
rows = _prepare_rows_for_push(rows)
rows = tqdm.tqdm(rows, 'PUSH', ascii=True, total=sum(counts.values()))
if stop_time:
rows = _add_stop_time(rows, stop_time)
if state:
rows = _check_push_state(context, rows, metadata)
if stop_row:
rows = itertools.islice(rows, stop_row)
rows = _push_to_remote_spinta(rows, creds, chunk_size, dry_run=dry_run)
if state and not dry_run:
rows = _save_push_state(context, rows, metadata)
while True:
try:
next(rows)
except StopIteration:
break
except:
if stop_on_error:
raise
log.exception("Error while reading data.")
class _PushRow:
model: Model
data: Dict[str, Any]
rev: Optional[str]
saved: bool = False
def __init__(self, model: Model, data: Dict[str, Any]):
self.model = model
self.data = data
self.rev = None
self.saved = False
def _prepare_rows_for_push(rows: Iterable[ModelRow]) -> Iterator[_PushRow]:
for model, row in rows:
_id = row['_id']
_type = row['_type']
where = {
'name': 'eq',
'args': [
{'name': 'bind', 'args': ['_id']},
_id,
]
}
payload = {
'_op': 'upsert',
'_type': _type,
'_id': _id,
'_where': spyna.unparse(where),
**{k: v for k, v in row.items() if not k.startswith('_')}
}
yield _PushRow(model, payload)
def _push_to_remote_spinta(
rows: Iterable[_PushRow],
creds: RemoteClientCredentials,
chunk_size: int,
*,
dry_run: bool = False,
stop_on_error: bool = False,
) -> Iterator[_PushRow]:
echo(f"Get access token from {creds.server}")
token = get_access_token(creds)
session = requests.Session()
session.headers['Content-Type'] = 'application/json'
session.headers['Authorization'] = f'Bearer {token}'
prefix = '{"_data":['
suffix = ']}'
slen = len(suffix)
chunk = prefix
ready = []
for row in rows:
data = fix_data_for_json(row.data)
data = json.dumps(data, ensure_ascii=False)
if ready and len(chunk) + len(data) + slen > chunk_size:
yield from _send_and_receive(
session,
creds.server,
ready,
chunk + suffix,
dry_run=dry_run,
stop_on_error=stop_on_error,
)
chunk = prefix
ready = []
chunk += (',' if ready else '') + data
ready.append(row)
if ready:
yield from _send_and_receive(
session,
creds.server,
ready,
chunk + suffix,
dry_run=dry_run,
stop_on_error=stop_on_error,
)
def _get_row_for_error(rows: List[_PushRow]) -> str:
size = len(rows)
if size > 0:
row = rows[0]
data = pprintpp.pformat(row.data)
return (
f" Model {row.model.name},"
f" items in chunk: {size},"
f" first item in chunk:\n {data}"
)
else:
return ''
def _send_and_receive(
session: requests.Session,
target: str,
rows: List[_PushRow],
data: str,
*,
dry_run: bool = False,
stop_on_error: bool = False,
) -> Iterator[_PushRow]:
if dry_run:
recv = _send_data_dry_run(data)
else:
recv = _send_data(
session,
target,
rows,
data,
stop_on_error=stop_on_error,
)
yield from _map_sent_and_recv(rows, recv)
def _send_data_dry_run(
data: str,
) -> Optional[List[Dict[str, Any]]]:
"""Pretend data has been sent to a target location."""
recv = json.loads(data)['_data']
for row in recv:
if '_id' not in row:
row['_id'] = str(uuid.uuid4())
row['_rev'] = str(uuid.uuid4())
return recv
def _send_data(
session: requests.Session,
target: str,
rows: List[_PushRow],
data: str,
*,
stop_on_error: bool = False,
) -> Optional[List[Dict[str, Any]]]:
data = data.encode('utf-8')
try:
resp = session.post(target, data=data)
except IOError as e:
if stop_on_error:
raise
log.error(
(
"Error when sending and receiving data.%s\n"
"Error: %s"
),
_get_row_for_error(rows),
e,
)
return
try:
resp.raise_for_status()
except HTTPError:
if stop_on_error:
raise
log.error(
(
"Error when sending and receiving data.%s\n"
"Server response (status=%s):\n%s"
),
_get_row_for_error(rows),
resp.status_code,
textwrap.indent(pprintpp.pformat(resp.json()), ' '),
)
return
return resp.json()['_data']
def _map_sent_and_recv(
sent: List[_PushRow],
recv: List[Dict[str, Any]],
) -> Iterator[_PushRow]:
assert len(sent) == len(recv), (
f"len(sent) = {len(sent)}, len(received) = {len(recv)}"
)
for sent_row, recv_row in zip(sent, recv):
assert sent_row.data['_id'] == recv_row['_id'], (
f"sent._id = {sent_row.data['_id']}, "
f"received._id = {recv_row['_id']}"
)
yield sent_row
def _add_stop_time(rows, stop):
start = time.time()
for row in rows:
yield row
if time.time() - start > stop:
break
def _init_push_state(
file: pathlib.Path,
models: List[Model],
) -> Tuple[sa.engine.Engine, sa.MetaData]:
engine = sa.create_engine(f'sqlite:///{file}')
metadata = sa.MetaData(engine)
for model in models:
table = sa.Table(
model.name, metadata,
sa.Column('id', sa.Unicode, primary_key=True),
sa.Column('rev', sa.Unicode),
sa.Column('pushed', sa.DateTime),
)
table.create(checkfirst=True)
return engine, metadata
def _get_model_type(row: _PushRow) -> str:
return row.data['_type']
def _check_push_state(
context: Context,
rows: Iterable[_PushRow],
metadata: sa.MetaData,
):
conn = context.get('push.state.conn')
for model_type, group in itertools.groupby(rows, key=_get_model_type):
table = metadata.tables[model_type]
query = sa.select([table.c.id, table.c.rev])
saved = {
state[table.c.id]: state[table.c.rev]
for state in conn.execute(query)
}
for row in group:
_id = row.data['_id']
rev = fix_data_for_json(take(row.data))
rev = flatten([rev])
rev = [[k, v] for x in rev for k, v in sorted(x.items())]
rev = msgpack.dumps(rev, strict_types=True)
rev = hashlib.sha1(rev).hexdigest()
row.rev = rev
row.saved = _id in saved
if saved.get(_id) == row.rev:
continue # Nothing has changed.
yield row
def _save_push_state(
context: Context,
rows: Iterable[_PushRow],
metadata: sa.MetaData,
):
conn = context.get('push.state.conn')
for row in rows:
table = metadata.tables[row.data['_type']]
if row.saved:
conn.execute(
table.update().
where(table.c.id == row.data['_id']).
values(
id=row.data['_id'],
rev=row.rev,
pushed=datetime.datetime.now(),
)
)
else:
conn.execute(
table.insert().
values(
id=row.data['_id'],
rev=row.rev,
pushed=datetime.datetime.now(),
)
)
yield row | 0.547585 | 0.100834 |
from mozinor.config.params import *
from mozinor.config.explain import *
Fast_Regressors = {
"DecisionTreeRegressor": {
"import": "sklearn.tree",
"criterion": ["mse", "mae"],
'max_depth': max_depth,
'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_leaf,
"show": DecisionTreeRegressor
},
"ExtraTreesRegressor": {
"import": "sklearn.ensemble",
'n_estimators': n_estimators,
"max_features": max_features,
"bootstrap": dual,
'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_leaf,
"show": ExtraTreesRegressor
},
"ElasticNetCV": {
"import": "sklearn.linear_model",
"l1_ratio": max_features,
"tol": learning_rate,
"show": ElasticNetCV
},
"LassoLarsCV": {
"import": "sklearn.linear_model",
"normalize": dual,
"show": LassoLarsCV
},
"RidgeCV": {
"import": "sklearn.linear_model",
"show": RidgeCV
},
'XGBRegressor': {
"import": "xgboost",
'n_estimators': n_estimators,
'max_depth': max_depth,
'learning_rate': learning_rate,
'subsample': max_features,
'min_child_weight': min_samples_leaf,
"show": XGBRegressor
}
}
Regressors = {
# Tree
"DecisionTreeRegressor": {
"import": "sklearn.tree",
"criterion": ["mse", "mae"],
'max_depth': max_depth,
'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_leaf,
"show": DecisionTreeRegressor
},
# Ensemble
"ExtraTreesRegressor": {
"import": "sklearn.ensemble",
'n_estimators': n_estimators,
"max_features": max_features,
"bootstrap": dual,
'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_leaf,
"show": ExtraTreesRegressor
},
"RandomForestRegressor": {
"import": "sklearn.ensemble",
'n_estimators': n_estimators,
"max_features": max_features,
"bootstrap": dual,
'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_leaf,
"show": RandomForestRegressor
},
"GradientBoostingRegressor": {
"import": "sklearn.ensemble",
'n_estimators': n_estimators,
"learning_rate": learning_rate,
"max_features": max_features,
"loss": gbloss,
"alpha": alpha,
'max_depth': max_depth,
'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_leaf,
"show": GradientBoostingRegressor
},
"AdaBoostRegressor": {
"import": "sklearn.ensemble",
'n_estimators': n_estimators,
"learning_rate": learning_rate,
"loss": adaloss,
"show": AdaBoostRegressor
},
# XGBoost
'XGBRegressor': {
"import": "xgboost",
'n_estimators': n_estimators,
'max_depth': max_depth,
'learning_rate': learning_rate,
'subsample': max_features,
'min_child_weight': min_samples_leaf,
"show": XGBRegressor
},
# Linear models
"ElasticNetCV": {
"import": "sklearn.linear_model",
"l1_ratio": max_features,
"tol": learning_rate,
"show": ElasticNetCV
},
"LassoLarsCV": {
"import": "sklearn.linear_model",
"normalize": dual,
"show": LassoLarsCV
},
"RidgeCV": {
"import": "sklearn.linear_model",
"show": RidgeCV
},
# Neighbors
"KNeighborsRegressor": {
"import": "sklearn.neighbors",
"weights": weights,
"p": [1, 2],
"n_neighbors": [50],
"show": KNeighborsRegressor
}
} | mozinor/config/regressors.py | from mozinor.config.params import *
from mozinor.config.explain import *
Fast_Regressors = {
"DecisionTreeRegressor": {
"import": "sklearn.tree",
"criterion": ["mse", "mae"],
'max_depth': max_depth,
'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_leaf,
"show": DecisionTreeRegressor
},
"ExtraTreesRegressor": {
"import": "sklearn.ensemble",
'n_estimators': n_estimators,
"max_features": max_features,
"bootstrap": dual,
'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_leaf,
"show": ExtraTreesRegressor
},
"ElasticNetCV": {
"import": "sklearn.linear_model",
"l1_ratio": max_features,
"tol": learning_rate,
"show": ElasticNetCV
},
"LassoLarsCV": {
"import": "sklearn.linear_model",
"normalize": dual,
"show": LassoLarsCV
},
"RidgeCV": {
"import": "sklearn.linear_model",
"show": RidgeCV
},
'XGBRegressor': {
"import": "xgboost",
'n_estimators': n_estimators,
'max_depth': max_depth,
'learning_rate': learning_rate,
'subsample': max_features,
'min_child_weight': min_samples_leaf,
"show": XGBRegressor
}
}
Regressors = {
# Tree
"DecisionTreeRegressor": {
"import": "sklearn.tree",
"criterion": ["mse", "mae"],
'max_depth': max_depth,
'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_leaf,
"show": DecisionTreeRegressor
},
# Ensemble
"ExtraTreesRegressor": {
"import": "sklearn.ensemble",
'n_estimators': n_estimators,
"max_features": max_features,
"bootstrap": dual,
'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_leaf,
"show": ExtraTreesRegressor
},
"RandomForestRegressor": {
"import": "sklearn.ensemble",
'n_estimators': n_estimators,
"max_features": max_features,
"bootstrap": dual,
'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_leaf,
"show": RandomForestRegressor
},
"GradientBoostingRegressor": {
"import": "sklearn.ensemble",
'n_estimators': n_estimators,
"learning_rate": learning_rate,
"max_features": max_features,
"loss": gbloss,
"alpha": alpha,
'max_depth': max_depth,
'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_leaf,
"show": GradientBoostingRegressor
},
"AdaBoostRegressor": {
"import": "sklearn.ensemble",
'n_estimators': n_estimators,
"learning_rate": learning_rate,
"loss": adaloss,
"show": AdaBoostRegressor
},
# XGBoost
'XGBRegressor': {
"import": "xgboost",
'n_estimators': n_estimators,
'max_depth': max_depth,
'learning_rate': learning_rate,
'subsample': max_features,
'min_child_weight': min_samples_leaf,
"show": XGBRegressor
},
# Linear models
"ElasticNetCV": {
"import": "sklearn.linear_model",
"l1_ratio": max_features,
"tol": learning_rate,
"show": ElasticNetCV
},
"LassoLarsCV": {
"import": "sklearn.linear_model",
"normalize": dual,
"show": LassoLarsCV
},
"RidgeCV": {
"import": "sklearn.linear_model",
"show": RidgeCV
},
# Neighbors
"KNeighborsRegressor": {
"import": "sklearn.neighbors",
"weights": weights,
"p": [1, 2],
"n_neighbors": [50],
"show": KNeighborsRegressor
}
} | 0.627381 | 0.536434 |
import os
import sys
from faker import Factory
sys.path.append(os.getcwd())
import api
import user
fake = Factory.create()
MOCK_NEW_USER = {
'name': '<NAME>',
'user_id': '3141592654',
'email': '<EMAIL>'
}
MOCK_SCAN = {
"env": {
"LANG": "en_US.UTF-8",
"AWS_DEFAULT_REGION": "eu-central-1",
"AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "128",
"AWS_LAMBDA_FUNCTION_NAME": "scheduled-serverless-profiler",
"AWS_SECRET_ACCESS_KEY": "<KEY>",
"AWS_LAMBDA_FUNCTION_VERSION": "$LATEST",
"PYTHONPATH": "/var/runtime",
"AWS_LAMBDA_LOG_GROUP_NAME": "/aws/lambda/scheduled-profiler",
"AWS_REGION": "eu-central-1",
"AWS_SESSION_TOKEN": "<PASSWORD>",
"LAMBDA_TASK_ROOT": "/var/task",
"AWS_EXECUTION_ENV": "AWS_Lambda_python2.7",
"AWS_SECURITY_TOKEN": "<PASSWORD>",
"LAMBDA_RUNTIME_DIR": "/var/runtime",
"AWS_LAMBDA_LOG_STREAM_NAME": "2017/03/11/[$LATEST]d5e2ca93",
"AWS_ACCESS_KEY_ID": "<KEY>",
"PATH": "/usr/local/bin:/usr/bin/:/bin"
}
}
def test_object_init():
a = api.APIKey('123567890')
assert a is not None
def test_api_key_location():
u = user.User(MOCK_NEW_USER)
result = u.find_or_create_by()
a = api.APIKey(result['api_key'])
search_operation = a.locate_user()
u.destroy()
assert search_operation['api_key'] is not None
assert search_operation['user_id'] == MOCK_NEW_USER['user_id']
assert search_operation['email'] == MOCK_NEW_USER['email']
assert search_operation['disabled'] is False
def test_profile_object():
u = user.User(MOCK_NEW_USER)
result = u.find_or_create_by()
p = api.Profiler(result['api_key'])
u.destroy()
assert p is not None
assert p.authenticated is True
def test_profile_storage():
u = user.User(MOCK_NEW_USER)
result = u.find_or_create_by()
p = api.Profiler(result['api_key'])
result = p.store_profile(MOCK_SCAN)
u.destroy()
assert p is not None
assert p.authenticated is True
assert result is not None
p.destroy_profile(result) | tests/test_api.py | import os
import sys
from faker import Factory
sys.path.append(os.getcwd())
import api
import user
fake = Factory.create()
MOCK_NEW_USER = {
'name': '<NAME>',
'user_id': '3141592654',
'email': '<EMAIL>'
}
MOCK_SCAN = {
"env": {
"LANG": "en_US.UTF-8",
"AWS_DEFAULT_REGION": "eu-central-1",
"AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "128",
"AWS_LAMBDA_FUNCTION_NAME": "scheduled-serverless-profiler",
"AWS_SECRET_ACCESS_KEY": "<KEY>",
"AWS_LAMBDA_FUNCTION_VERSION": "$LATEST",
"PYTHONPATH": "/var/runtime",
"AWS_LAMBDA_LOG_GROUP_NAME": "/aws/lambda/scheduled-profiler",
"AWS_REGION": "eu-central-1",
"AWS_SESSION_TOKEN": "<PASSWORD>",
"LAMBDA_TASK_ROOT": "/var/task",
"AWS_EXECUTION_ENV": "AWS_Lambda_python2.7",
"AWS_SECURITY_TOKEN": "<PASSWORD>",
"LAMBDA_RUNTIME_DIR": "/var/runtime",
"AWS_LAMBDA_LOG_STREAM_NAME": "2017/03/11/[$LATEST]d5e2ca93",
"AWS_ACCESS_KEY_ID": "<KEY>",
"PATH": "/usr/local/bin:/usr/bin/:/bin"
}
}
def test_object_init():
a = api.APIKey('123567890')
assert a is not None
def test_api_key_location():
u = user.User(MOCK_NEW_USER)
result = u.find_or_create_by()
a = api.APIKey(result['api_key'])
search_operation = a.locate_user()
u.destroy()
assert search_operation['api_key'] is not None
assert search_operation['user_id'] == MOCK_NEW_USER['user_id']
assert search_operation['email'] == MOCK_NEW_USER['email']
assert search_operation['disabled'] is False
def test_profile_object():
u = user.User(MOCK_NEW_USER)
result = u.find_or_create_by()
p = api.Profiler(result['api_key'])
u.destroy()
assert p is not None
assert p.authenticated is True
def test_profile_storage():
u = user.User(MOCK_NEW_USER)
result = u.find_or_create_by()
p = api.Profiler(result['api_key'])
result = p.store_profile(MOCK_SCAN)
u.destroy()
assert p is not None
assert p.authenticated is True
assert result is not None
p.destroy_profile(result) | 0.197444 | 0.123656 |
import sys, os, socket, time
def auto_help(name,rank,description):
stbl = " " + name + " "*(13-len(name)+4) + rank + " "*(8-len(rank)+4) + description
return stbl
def auto_targ(targetlist):
print "Vulnrable Applications (%s)\n" %name
print " ID Device"
print " -- ------"
for _ in targetlist:
print " "+_+" "*(9-len(_))+targetlist[_]
print
try:
if desc == "get-id":
print auto_help("BufferOverflow","Normal","Simple Remote BufferOverflow")
except:
pass
def auto_info(name,module,plat,priv,lic,rank,release="N/A",by="N/A"):
print "\nPublisher Information for %s" %name
print
print " Name:",name
print " Module:",module
print " Platform:",plat
print " Privileged:",priv
print " License:",lic
print " Rank:",rank
print " Disclosed:",release
def auto_opt(name,cset,req,description):
stbl = " " + name + " "*(9-len(name)) + cset + " "*(15-len(cset)+2) + req + " "*(8-len(req)+2) + description
print stbl
try: BUF
except: BUF = 1024
try: RHOST
except: pass
try: RPORT
except: RPORT = 23
try: TIMEOUT
except: TIMEOUT = 5
def attack(RHOST,BUF=1025,RPORT=23,TIMEOUT=5):
for _ in range(1):
"Actions Here"
pass
def show_opt():
print "\nModule Options (Example)\n"
print " Name Current Setting Required Description"
print " ---- --------------- -------- -----------"
try:
auto_opt("BUF",str(BUF),"no","Buffer Size")
except:
auto_opt("BUF"," ","no","Total Buffer Size")
try:
auto_opt("RHOST",RHOST,"yes", "Target Host")
except:
auto_opt("RHOST"," ","yes", "Target Host")
try:
auto_opt("RPORT",str(RPORT),"yes", "Target Port")
except:
auto_opt("RPORT"," ","yes", "Target Port")
try:
auto_opt("TIMEOUT", str(TIMEOUT),"no", "Timeout Time")
except:
auto_opt("TIMEOUT"," ","no", "Timelout Time")
print
try:
if desc == "get-opt":
show_opt()
except:
pass
try:
if desc == "proc":
try:
if RHOST and RPORT and TIMEOUT and BUF:
attack(RHOST,int(BUF),int(RPORT), int(TIMEOUT))
except Exception as e:
print e
print "Options Still Unset"
time.sleep(0.3)
show_opt()
except:
pass
try:
if desc == "get-info":
auto_info(name,"Example","Python 2.7","No","IDGAF License","Normal")
show_opt()
targets = {"1":"PacMan SSH","2":"Simple Socket Servers"}
auto_targ(targets)
except:
pass | example_api.py | import sys, os, socket, time
def auto_help(name,rank,description):
stbl = " " + name + " "*(13-len(name)+4) + rank + " "*(8-len(rank)+4) + description
return stbl
def auto_targ(targetlist):
print "Vulnrable Applications (%s)\n" %name
print " ID Device"
print " -- ------"
for _ in targetlist:
print " "+_+" "*(9-len(_))+targetlist[_]
print
try:
if desc == "get-id":
print auto_help("BufferOverflow","Normal","Simple Remote BufferOverflow")
except:
pass
def auto_info(name,module,plat,priv,lic,rank,release="N/A",by="N/A"):
print "\nPublisher Information for %s" %name
print
print " Name:",name
print " Module:",module
print " Platform:",plat
print " Privileged:",priv
print " License:",lic
print " Rank:",rank
print " Disclosed:",release
def auto_opt(name,cset,req,description):
stbl = " " + name + " "*(9-len(name)) + cset + " "*(15-len(cset)+2) + req + " "*(8-len(req)+2) + description
print stbl
try: BUF
except: BUF = 1024
try: RHOST
except: pass
try: RPORT
except: RPORT = 23
try: TIMEOUT
except: TIMEOUT = 5
def attack(RHOST,BUF=1025,RPORT=23,TIMEOUT=5):
for _ in range(1):
"Actions Here"
pass
def show_opt():
print "\nModule Options (Example)\n"
print " Name Current Setting Required Description"
print " ---- --------------- -------- -----------"
try:
auto_opt("BUF",str(BUF),"no","Buffer Size")
except:
auto_opt("BUF"," ","no","Total Buffer Size")
try:
auto_opt("RHOST",RHOST,"yes", "Target Host")
except:
auto_opt("RHOST"," ","yes", "Target Host")
try:
auto_opt("RPORT",str(RPORT),"yes", "Target Port")
except:
auto_opt("RPORT"," ","yes", "Target Port")
try:
auto_opt("TIMEOUT", str(TIMEOUT),"no", "Timeout Time")
except:
auto_opt("TIMEOUT"," ","no", "Timelout Time")
print
try:
if desc == "get-opt":
show_opt()
except:
pass
try:
if desc == "proc":
try:
if RHOST and RPORT and TIMEOUT and BUF:
attack(RHOST,int(BUF),int(RPORT), int(TIMEOUT))
except Exception as e:
print e
print "Options Still Unset"
time.sleep(0.3)
show_opt()
except:
pass
try:
if desc == "get-info":
auto_info(name,"Example","Python 2.7","No","IDGAF License","Normal")
show_opt()
targets = {"1":"PacMan SSH","2":"Simple Socket Servers"}
auto_targ(targets)
except:
pass | 0.066255 | 0.061678 |
import datetime
import logging
import os
from airflow import configuration
from airflow import models
from airflow.contrib.hooks import gcs_hook
from airflow.contrib.operators import dataflow_operator
from airflow.operators import python_operator
from airflow.utils.trigger_rule import TriggerRule
# Set start_date of the DAG to the -1 day. This will
# make the DAG immediately available for scheduling.
YESTERDAY = datetime.datetime.combine(
datetime.datetime.today() - datetime.timedelta(1),
datetime.datetime.min.time())
SUCCESS_TAG = 'success.txt'
FAILURE_TAG = 'failure.txt'
# Reads environment variables set as part of the airflow pipeline.
# The following Airflow variables are set:
# gcp_project: Google Cloud Platform project id.
# dataflow_template_location: GCS location of Dataflow template.
# dataflow_staging_location: GCS location of stagining directory for Dataflow.
# email: Email address to send failure notifications.
# completion_status_file_bucket: Path of GCS file to be updated on airflow completion.
config = models.Variable.get("variables_config", deserialize_json=True)
# Default arguments for airflow task. It is recommended to specify dataflow args
# here, instead of in dataflow job config.
DEFAULT_DAG_ARGS = {
'start_date': YESTERDAY,
'email': config['email'],
'email_on_failure': True,
'email_on_retry': False,
'retries': 0,
'project_id': config['gcp_project'],
'dataflow_default_options': {
'project': config['gcp_project'],
'template_location': config['dataflow_template_location'],
'runner': 'DataflowRunner',
'region': 'us-central1',
'zone': 'us-central1-a',
'ip_configuration': 'WORKER_IP_PRIVATE',
'staging_location': config['dataflow_staging_location'],
'no_use_public_ips': True,
}
}
def update_on_completion(src, dst, **kwargs):
"""Write to GCS on completion of dataflow task.
Update the completion status. This writes to either success.txt or
failure.txt. gcs_hook doesn't have update api, so we use copy.
"""
conn = gcs_hook.GoogleCloudStorageHook()
bucket = config['completion_status_file_bucket']
conn.copy(bucket, dst, bucket, src)
with models.DAG(dag_id='GcsToBTCache',
description='A DAG triggered by an external Cloud Function',
schedule_interval=None, default_args=DEFAULT_DAG_ARGS) as dag:
# Build arguments for dataflow task. The dag_run.conf is a way of accessing
# input variables passed by calling GCF function.
job_args = {
'bigtableInstanceId': config['bt_instance'],
'bigtableTableId': '{{ dag_run.conf["bigtable_id"] }}',
'inputFile': '{{ dag_run.conf["input_file"] }}',
'bigtableProjectId': config['gcp_project'],
}
# Main Dataflow task that will process and load the input csv file.
dataflow_task = dataflow_operator.DataflowTemplateOperator(
task_id='csv_to_bt',
template=config['dataflow_template_location'],
parameters=job_args)
success_task = python_operator.PythonOperator(task_id='success-move-to-completion',
python_callable=update_on_completion,
op_args=[SUCCESS_TAG, FAILURE_TAG],
provide_context=True,
trigger_rule=TriggerRule.ALL_SUCCESS)
failure_task = python_operator.PythonOperator(task_id='failure-move-to-completion',
python_callable=update_on_completion,
op_args=[FAILURE_TAG, SUCCESS_TAG],
provide_context=True,
trigger_rule=TriggerRule.ALL_FAILED)
# The success_task and failure_task both wait on completion of
# dataflow_task.
dataflow_task >> success_task
dataflow_task >> failure_task | cloud_automation/airflow/dag.py | import datetime
import logging
import os
from airflow import configuration
from airflow import models
from airflow.contrib.hooks import gcs_hook
from airflow.contrib.operators import dataflow_operator
from airflow.operators import python_operator
from airflow.utils.trigger_rule import TriggerRule
# Set start_date of the DAG to the -1 day. This will
# make the DAG immediately available for scheduling.
YESTERDAY = datetime.datetime.combine(
datetime.datetime.today() - datetime.timedelta(1),
datetime.datetime.min.time())
SUCCESS_TAG = 'success.txt'
FAILURE_TAG = 'failure.txt'
# Reads environment variables set as part of the airflow pipeline.
# The following Airflow variables are set:
# gcp_project: Google Cloud Platform project id.
# dataflow_template_location: GCS location of Dataflow template.
# dataflow_staging_location: GCS location of stagining directory for Dataflow.
# email: Email address to send failure notifications.
# completion_status_file_bucket: Path of GCS file to be updated on airflow completion.
config = models.Variable.get("variables_config", deserialize_json=True)
# Default arguments for airflow task. It is recommended to specify dataflow args
# here, instead of in dataflow job config.
DEFAULT_DAG_ARGS = {
'start_date': YESTERDAY,
'email': config['email'],
'email_on_failure': True,
'email_on_retry': False,
'retries': 0,
'project_id': config['gcp_project'],
'dataflow_default_options': {
'project': config['gcp_project'],
'template_location': config['dataflow_template_location'],
'runner': 'DataflowRunner',
'region': 'us-central1',
'zone': 'us-central1-a',
'ip_configuration': 'WORKER_IP_PRIVATE',
'staging_location': config['dataflow_staging_location'],
'no_use_public_ips': True,
}
}
def update_on_completion(src, dst, **kwargs):
"""Write to GCS on completion of dataflow task.
Update the completion status. This writes to either success.txt or
failure.txt. gcs_hook doesn't have update api, so we use copy.
"""
conn = gcs_hook.GoogleCloudStorageHook()
bucket = config['completion_status_file_bucket']
conn.copy(bucket, dst, bucket, src)
with models.DAG(dag_id='GcsToBTCache',
description='A DAG triggered by an external Cloud Function',
schedule_interval=None, default_args=DEFAULT_DAG_ARGS) as dag:
# Build arguments for dataflow task. The dag_run.conf is a way of accessing
# input variables passed by calling GCF function.
job_args = {
'bigtableInstanceId': config['bt_instance'],
'bigtableTableId': '{{ dag_run.conf["bigtable_id"] }}',
'inputFile': '{{ dag_run.conf["input_file"] }}',
'bigtableProjectId': config['gcp_project'],
}
# Main Dataflow task that will process and load the input csv file.
dataflow_task = dataflow_operator.DataflowTemplateOperator(
task_id='csv_to_bt',
template=config['dataflow_template_location'],
parameters=job_args)
success_task = python_operator.PythonOperator(task_id='success-move-to-completion',
python_callable=update_on_completion,
op_args=[SUCCESS_TAG, FAILURE_TAG],
provide_context=True,
trigger_rule=TriggerRule.ALL_SUCCESS)
failure_task = python_operator.PythonOperator(task_id='failure-move-to-completion',
python_callable=update_on_completion,
op_args=[FAILURE_TAG, SUCCESS_TAG],
provide_context=True,
trigger_rule=TriggerRule.ALL_FAILED)
# The success_task and failure_task both wait on completion of
# dataflow_task.
dataflow_task >> success_task
dataflow_task >> failure_task | 0.360377 | 0.29626 |
import os
import time
import hmac
from hashlib import md5
from collections import UserDict
from threading import RLock, Lock
from starlette.config import Config
from starlette.templating import Jinja2Templates
templates = Jinja2Templates(directory='web/templates')
async def exception_custom(req, exce_info: int):
template = "exception.html"
context = {"request": req, "code": exce_info}
return templates.TemplateResponse(template, context, status_code=401)
async def exception_401(req, exc):
template = "exception.html"
context = {"request": req, "code": 401}
return templates.TemplateResponse(template, context, status_code=401)
async def exception_404(req, exc):
template = "exception.html"
context = {"request": req, "code": 404}
return templates.TemplateResponse(template, context, status_code=404)
async def exception_500(req, exc):
template = "exception.html"
context = {"request": req, "code": 500}
return templates.TemplateResponse(template, context, status_code=500)
def md5_salt(salt: str, encryption_data: str) -> str:
hash_instance = md5(bytes(salt, encoding="utf-8"))
hash_instance.update(bytes(encryption_data, encoding="utf-8"))
v = hash_instance.hexdigest()
return v
def hmac_salt(salt: str, encryption_data: str) -> str:
hmac_instance = hmac.new(key=(bytes(salt, encoding="utf-8")), msg=None, digestmod='MD5')
hmac_instance.update(bytes(encryption_data, encoding="utf-8"))
v = hmac_instance.hexdigest()
return v
class TTL(UserDict):
def __init__(self, *args, **kwargs):
self._rlock = RLock()
self._lock = Lock()
super().__init__(*args, **kwargs)
def __repr__(self):
return '<TTLDict:{} {} '.format(id(self), self.data)
def __expire__(self, key, ttl, now=None):
if now is None:
now = time.time()
with self._rlock:
_expire, value = self.data[key]
self.data[key] = (now + ttl, value)
def ttl(self, key: str, now=None):
if now is None:
now = time.time()
with self._rlock:
expire, value = self.data.get(key, (None, None))
if expire is None:
return -1
elif expire <= now:
del self[key]
return -2
return expire - now
def setex(self, key: str, value: str, ttl: int):
with self._rlock:
expire = time.time() + ttl
self.data[key] = (expire, value)
def __len__(self):
with self._rlock:
for key in list(self.data.keys()):
self.ttl(key)
return len(self.data)
def __iter__(self):
with self._rlock:
for k in self.data.keys():
ttl = self.ttl(k)
if ttl != -2:
yield k
def __setitem__(self, key, value):
with self._lock:
self.data[key] = (None, value)
def __delitem__(self, key):
with self._lock:
del self.data[key]
def __getitem__(self, key):
with self._rlock:
self.ttl(key)
return self.data[key][1]
def config_info(key: str, default_value=None):
env = os.getenv("env", "dev")
config = Config(".env_{}".format(env))
value = config(key, default=default_value)
return value | web/utils.py | import os
import time
import hmac
from hashlib import md5
from collections import UserDict
from threading import RLock, Lock
from starlette.config import Config
from starlette.templating import Jinja2Templates
templates = Jinja2Templates(directory='web/templates')
async def exception_custom(req, exce_info: int):
template = "exception.html"
context = {"request": req, "code": exce_info}
return templates.TemplateResponse(template, context, status_code=401)
async def exception_401(req, exc):
template = "exception.html"
context = {"request": req, "code": 401}
return templates.TemplateResponse(template, context, status_code=401)
async def exception_404(req, exc):
template = "exception.html"
context = {"request": req, "code": 404}
return templates.TemplateResponse(template, context, status_code=404)
async def exception_500(req, exc):
template = "exception.html"
context = {"request": req, "code": 500}
return templates.TemplateResponse(template, context, status_code=500)
def md5_salt(salt: str, encryption_data: str) -> str:
hash_instance = md5(bytes(salt, encoding="utf-8"))
hash_instance.update(bytes(encryption_data, encoding="utf-8"))
v = hash_instance.hexdigest()
return v
def hmac_salt(salt: str, encryption_data: str) -> str:
hmac_instance = hmac.new(key=(bytes(salt, encoding="utf-8")), msg=None, digestmod='MD5')
hmac_instance.update(bytes(encryption_data, encoding="utf-8"))
v = hmac_instance.hexdigest()
return v
class TTL(UserDict):
def __init__(self, *args, **kwargs):
self._rlock = RLock()
self._lock = Lock()
super().__init__(*args, **kwargs)
def __repr__(self):
return '<TTLDict:{} {} '.format(id(self), self.data)
def __expire__(self, key, ttl, now=None):
if now is None:
now = time.time()
with self._rlock:
_expire, value = self.data[key]
self.data[key] = (now + ttl, value)
def ttl(self, key: str, now=None):
if now is None:
now = time.time()
with self._rlock:
expire, value = self.data.get(key, (None, None))
if expire is None:
return -1
elif expire <= now:
del self[key]
return -2
return expire - now
def setex(self, key: str, value: str, ttl: int):
with self._rlock:
expire = time.time() + ttl
self.data[key] = (expire, value)
def __len__(self):
with self._rlock:
for key in list(self.data.keys()):
self.ttl(key)
return len(self.data)
def __iter__(self):
with self._rlock:
for k in self.data.keys():
ttl = self.ttl(k)
if ttl != -2:
yield k
def __setitem__(self, key, value):
with self._lock:
self.data[key] = (None, value)
def __delitem__(self, key):
with self._lock:
del self.data[key]
def __getitem__(self, key):
with self._rlock:
self.ttl(key)
return self.data[key][1]
def config_info(key: str, default_value=None):
env = os.getenv("env", "dev")
config = Config(".env_{}".format(env))
value = config(key, default=default_value)
return value | 0.515376 | 0.091544 |
from .enum_loader import enum_loader
from bes.common.string_util import string_util
from bes.system.compat import with_metaclass
class _flag_enum_meta_class(type):
'cheesy enum. Id rather use the one in python3 but i want to support python 2.7 with no exta deps.'
def __new__(meta, name, bases, class_dict):
clazz = type.__new__(meta, name, bases, class_dict)
if hasattr(clazz, '_ENUM'):
raise RuntimeError('subclassing %s not allowed.' % (bases[-1]))
e = enum_loader.load(clazz)
if e:
clazz._ENUM = e
masks = []
for i in range(0, clazz.SIZE * 8):
masks.append(0x1 << i)
setattr(clazz, 'MASKS', masks)
class constants(object):
pass
for n in clazz._ENUM.name_values:
setattr(constants, n.name, n.value)
clazz.CONSTANTS = constants
return clazz
class flag_enum(with_metaclass(_flag_enum_meta_class, object)):
DELIMITER = '|'
def __init__(self, value = 0):
self.assign(value)
def matches(self, mask):
return (self.value & mask) != 0
def __str__(self):
v = []
for n in self._ENUM.name_values:
if n.value in self.MASKS:
if self.matches(n.value):
v.append(n.name)
return self.DELIMITER.join(sorted(v))
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.value == other.value
elif string_util.is_string(other):
return self.value == self.parse(other)
elif isinstance(other, int):
return self.value == other
else:
raise TypeError('invalid other: %s - %s' % (str(other), type(other)))
@classmethod
def value_is_valid(clazz, value):
return self._ENUM.value_is_valid(value)
@classmethod
def name_is_valid(clazz, name):
return self._ENUM.name_is_valid(name)
def assign(self, what):
if isinstance(what, self.__class__):
self.value = what.value
elif string_util.is_string(what):
self.value = self.parse(what)
elif isinstance(what, int):
self.value = what
else:
raise TypeError('invalid value: %s' % (str(what)))
@property
def value(self):
return self._value
@value.setter
def value(self, value):
assert isinstance(value, int)
self._value = value
@property
def name(self):
return self._ENUM.value_to_name(self._value)
@name.setter
def name(self, name):
self._ENUM.check_name(name)
self.value = self._ENUM.name_to_value(name)
@classmethod
def parse(clazz, s):
if not string_util.is_string(s):
raise TypeError('mask to parse should be a string instead of: %s - %s' % (str(s), type(s)))
names = s.split(clazz.DELIMITER)
names = [ n.strip() for n in names if n.strip() ]
result = 0
for name in names:
value = clazz._ENUM.parse_name(name)
if value == None:
raise ValueError('invalid value: %s' % (name))
result |= value
return result | lib/bes/enum/flag_enum.py |
from .enum_loader import enum_loader
from bes.common.string_util import string_util
from bes.system.compat import with_metaclass
class _flag_enum_meta_class(type):
'cheesy enum. Id rather use the one in python3 but i want to support python 2.7 with no exta deps.'
def __new__(meta, name, bases, class_dict):
clazz = type.__new__(meta, name, bases, class_dict)
if hasattr(clazz, '_ENUM'):
raise RuntimeError('subclassing %s not allowed.' % (bases[-1]))
e = enum_loader.load(clazz)
if e:
clazz._ENUM = e
masks = []
for i in range(0, clazz.SIZE * 8):
masks.append(0x1 << i)
setattr(clazz, 'MASKS', masks)
class constants(object):
pass
for n in clazz._ENUM.name_values:
setattr(constants, n.name, n.value)
clazz.CONSTANTS = constants
return clazz
class flag_enum(with_metaclass(_flag_enum_meta_class, object)):
DELIMITER = '|'
def __init__(self, value = 0):
self.assign(value)
def matches(self, mask):
return (self.value & mask) != 0
def __str__(self):
v = []
for n in self._ENUM.name_values:
if n.value in self.MASKS:
if self.matches(n.value):
v.append(n.name)
return self.DELIMITER.join(sorted(v))
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.value == other.value
elif string_util.is_string(other):
return self.value == self.parse(other)
elif isinstance(other, int):
return self.value == other
else:
raise TypeError('invalid other: %s - %s' % (str(other), type(other)))
@classmethod
def value_is_valid(clazz, value):
return self._ENUM.value_is_valid(value)
@classmethod
def name_is_valid(clazz, name):
return self._ENUM.name_is_valid(name)
def assign(self, what):
if isinstance(what, self.__class__):
self.value = what.value
elif string_util.is_string(what):
self.value = self.parse(what)
elif isinstance(what, int):
self.value = what
else:
raise TypeError('invalid value: %s' % (str(what)))
@property
def value(self):
return self._value
@value.setter
def value(self, value):
assert isinstance(value, int)
self._value = value
@property
def name(self):
return self._ENUM.value_to_name(self._value)
@name.setter
def name(self, name):
self._ENUM.check_name(name)
self.value = self._ENUM.name_to_value(name)
@classmethod
def parse(clazz, s):
if not string_util.is_string(s):
raise TypeError('mask to parse should be a string instead of: %s - %s' % (str(s), type(s)))
names = s.split(clazz.DELIMITER)
names = [ n.strip() for n in names if n.strip() ]
result = 0
for name in names:
value = clazz._ENUM.parse_name(name)
if value == None:
raise ValueError('invalid value: %s' % (name))
result |= value
return result | 0.634656 | 0.154695 |
import numpy as np
from collections import OrderedDict, deque
import warnings
import dm_env
from dm_env import specs
from dm_control import suite
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=DeprecationWarning)
from dm_control import manipulation
from dm_control.suite.wrappers import action_scale, pixels
MANIP_PIXELS_KEY = 'front_close'
class FlattenObservationWrapper(dm_env.Environment):
def __init__(self, env):
self._env = env
self._obs_spec = OrderedDict()
wrapped_obs_spec = env.observation_spec().copy()
dim = 0
for key in wrapped_obs_spec.keys():
if key != MANIP_PIXELS_KEY:
spec = wrapped_obs_spec[key]
assert spec.dtype == np.float64
assert type(spec) == specs.Array
dim += np.prod(spec.shape)
self._obs_spec['features'] = specs.Array(shape=(dim,),
dtype=np.float32,
name='features')
if MANIP_PIXELS_KEY in wrapped_obs_spec:
spec = wrapped_obs_spec[MANIP_PIXELS_KEY]
self._obs_spec['pixels'] = specs.BoundedArray(shape=spec.shape[1:],
dtype=spec.dtype,
minimum=spec.minimum,
maximum=spec.maximum,
name='pixels')
self._obs_spec['state'] = specs.Array(
shape=self._env.physics.get_state().shape,
dtype=np.float32,
name='state')
def _transform_observation(self, time_step):
obs = OrderedDict()
features = []
for key, value in time_step.observation.items():
if key != MANIP_PIXELS_KEY:
features.append(value.ravel())
obs['features'] = np.concatenate(features, axis=0)
obs['state'] = self._env.physics.get_state().copy()
if MANIP_PIXELS_KEY in time_step.observation:
obs['pixels'] = time_step.observation[MANIP_PIXELS_KEY][0]
return time_step._replace(observation=obs)
def reset(self):
time_step = self._env.reset()
return self._transform_observation(time_step)
def step(self, action):
time_step = self._env.step(action)
return self._transform_observation(time_step)
def observation_spec(self):
return self._obs_spec
def action_spec(self):
return self._env.action_spec()
def __getattr__(self, name):
return getattr(self._env, name)
class FrameStackWrapper(dm_env.Environment):
def __init__(self, env, k):
self._env = env
self._k = k
self._frames = deque([], maxlen=k)
wrapped_obs_spec = env.observation_spec()
assert 'features' in wrapped_obs_spec
assert 'pixels' in wrapped_obs_spec
self._obs_spec = OrderedDict()
self._obs_spec['features'] = wrapped_obs_spec['features']
self._obs_spec['state'] = wrapped_obs_spec['state']
pixels_spec = wrapped_obs_spec['pixels']
self._obs_spec['pixels'] = specs.BoundedArray(shape=np.concatenate(
[[pixels_spec.shape[2] * k], pixels_spec.shape[:2]], axis=0),
dtype=pixels_spec.dtype,
minimum=0,
maximum=255,
name=pixels_spec.name)
def _transform_observation(self, time_step):
assert len(self._frames) == self._k
obs = OrderedDict()
obs['features'] = time_step.observation['features']
obs['state'] = time_step.observation['state']
obs['pixels'] = np.concatenate(list(self._frames), axis=0)
return time_step._replace(observation=obs)
def reset(self):
time_step = self._env.reset()
pixels = time_step.observation['pixels'].transpose(2, 0, 1).copy()
for _ in range(self._k):
self._frames.append(pixels.copy())
return self._transform_observation(time_step)
def step(self, action):
time_step = self._env.step(action)
self._frames.append(time_step.observation['pixels'].transpose(
2, 0, 1).copy())
return self._transform_observation(time_step)
def observation_spec(self):
return self._obs_spec
def action_spec(self):
return self._env.action_spec()
def __getattr__(self, name):
return getattr(self._env, name)
class ActionRepeatWrapper(dm_env.Environment):
def __init__(self, env, amount):
self._env = env
self._amount = amount
def step(self, action):
reward = 0.0
for i in range(self._amount):
time_step = self._env.step(action)
reward += time_step.reward or 0.0
if time_step.last():
break
return time_step._replace(reward=reward)
def observation_spec(self):
return self._env.observation_spec()
def action_spec(self):
return self._env.action_spec()
def reset(self):
return self._env.reset()
def __getattr__(self, name):
return getattr(self._env, name)
def split_env_name(env_name):
if env_name == 'ball_in_cup_catch':
return 'ball_in_cup', 'catch'
if env_name.startswith('point_mass'):
return 'point_mass', env_name.split('_')[-1]
domain = env_name.split('_')[0]
task = '_'.join(env_name.split('_')[1:])
return domain, task
def make(env_name, frame_stack, action_repeat, seed):
domain, task = split_env_name(env_name)
if domain == 'manip':
env = manipulation.load(f'{task}_vision', seed=seed)
else:
env = suite.load(domain,
task,
task_kwargs={'random': seed},
visualize_reward=False)
# apply action repeat and scaling
env = ActionRepeatWrapper(env, action_repeat)
env = action_scale.Wrapper(env, minimum=-1.0, maximum=+1.0)
# flatten features
env = FlattenObservationWrapper(env)
if domain != 'manip':
# per dreamer: https://github.com/danijar/dreamer/blob/02f0210f5991c7710826ca7881f19c64a012290c/wrappers.py#L26
camera_id = 2 if domain == 'quadruped' else 0
render_kwargs = {'height': 84, 'width': 84, 'camera_id': camera_id}
env = pixels.Wrapper(env,
pixels_only=False,
render_kwargs=render_kwargs)
env = FrameStackWrapper(env, frame_stack)
action_spec = env.action_spec()
assert np.all(action_spec.minimum >= -1.0)
assert np.all(action_spec.maximum <= +1.0)
return env | dmc.py | import numpy as np
from collections import OrderedDict, deque
import warnings
import dm_env
from dm_env import specs
from dm_control import suite
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=DeprecationWarning)
from dm_control import manipulation
from dm_control.suite.wrappers import action_scale, pixels
MANIP_PIXELS_KEY = 'front_close'
class FlattenObservationWrapper(dm_env.Environment):
def __init__(self, env):
self._env = env
self._obs_spec = OrderedDict()
wrapped_obs_spec = env.observation_spec().copy()
dim = 0
for key in wrapped_obs_spec.keys():
if key != MANIP_PIXELS_KEY:
spec = wrapped_obs_spec[key]
assert spec.dtype == np.float64
assert type(spec) == specs.Array
dim += np.prod(spec.shape)
self._obs_spec['features'] = specs.Array(shape=(dim,),
dtype=np.float32,
name='features')
if MANIP_PIXELS_KEY in wrapped_obs_spec:
spec = wrapped_obs_spec[MANIP_PIXELS_KEY]
self._obs_spec['pixels'] = specs.BoundedArray(shape=spec.shape[1:],
dtype=spec.dtype,
minimum=spec.minimum,
maximum=spec.maximum,
name='pixels')
self._obs_spec['state'] = specs.Array(
shape=self._env.physics.get_state().shape,
dtype=np.float32,
name='state')
def _transform_observation(self, time_step):
obs = OrderedDict()
features = []
for key, value in time_step.observation.items():
if key != MANIP_PIXELS_KEY:
features.append(value.ravel())
obs['features'] = np.concatenate(features, axis=0)
obs['state'] = self._env.physics.get_state().copy()
if MANIP_PIXELS_KEY in time_step.observation:
obs['pixels'] = time_step.observation[MANIP_PIXELS_KEY][0]
return time_step._replace(observation=obs)
def reset(self):
time_step = self._env.reset()
return self._transform_observation(time_step)
def step(self, action):
time_step = self._env.step(action)
return self._transform_observation(time_step)
def observation_spec(self):
return self._obs_spec
def action_spec(self):
return self._env.action_spec()
def __getattr__(self, name):
return getattr(self._env, name)
class FrameStackWrapper(dm_env.Environment):
def __init__(self, env, k):
self._env = env
self._k = k
self._frames = deque([], maxlen=k)
wrapped_obs_spec = env.observation_spec()
assert 'features' in wrapped_obs_spec
assert 'pixels' in wrapped_obs_spec
self._obs_spec = OrderedDict()
self._obs_spec['features'] = wrapped_obs_spec['features']
self._obs_spec['state'] = wrapped_obs_spec['state']
pixels_spec = wrapped_obs_spec['pixels']
self._obs_spec['pixels'] = specs.BoundedArray(shape=np.concatenate(
[[pixels_spec.shape[2] * k], pixels_spec.shape[:2]], axis=0),
dtype=pixels_spec.dtype,
minimum=0,
maximum=255,
name=pixels_spec.name)
def _transform_observation(self, time_step):
assert len(self._frames) == self._k
obs = OrderedDict()
obs['features'] = time_step.observation['features']
obs['state'] = time_step.observation['state']
obs['pixels'] = np.concatenate(list(self._frames), axis=0)
return time_step._replace(observation=obs)
def reset(self):
time_step = self._env.reset()
pixels = time_step.observation['pixels'].transpose(2, 0, 1).copy()
for _ in range(self._k):
self._frames.append(pixels.copy())
return self._transform_observation(time_step)
def step(self, action):
time_step = self._env.step(action)
self._frames.append(time_step.observation['pixels'].transpose(
2, 0, 1).copy())
return self._transform_observation(time_step)
def observation_spec(self):
return self._obs_spec
def action_spec(self):
return self._env.action_spec()
def __getattr__(self, name):
return getattr(self._env, name)
class ActionRepeatWrapper(dm_env.Environment):
def __init__(self, env, amount):
self._env = env
self._amount = amount
def step(self, action):
reward = 0.0
for i in range(self._amount):
time_step = self._env.step(action)
reward += time_step.reward or 0.0
if time_step.last():
break
return time_step._replace(reward=reward)
def observation_spec(self):
return self._env.observation_spec()
def action_spec(self):
return self._env.action_spec()
def reset(self):
return self._env.reset()
def __getattr__(self, name):
return getattr(self._env, name)
def split_env_name(env_name):
if env_name == 'ball_in_cup_catch':
return 'ball_in_cup', 'catch'
if env_name.startswith('point_mass'):
return 'point_mass', env_name.split('_')[-1]
domain = env_name.split('_')[0]
task = '_'.join(env_name.split('_')[1:])
return domain, task
def make(env_name, frame_stack, action_repeat, seed):
domain, task = split_env_name(env_name)
if domain == 'manip':
env = manipulation.load(f'{task}_vision', seed=seed)
else:
env = suite.load(domain,
task,
task_kwargs={'random': seed},
visualize_reward=False)
# apply action repeat and scaling
env = ActionRepeatWrapper(env, action_repeat)
env = action_scale.Wrapper(env, minimum=-1.0, maximum=+1.0)
# flatten features
env = FlattenObservationWrapper(env)
if domain != 'manip':
# per dreamer: https://github.com/danijar/dreamer/blob/02f0210f5991c7710826ca7881f19c64a012290c/wrappers.py#L26
camera_id = 2 if domain == 'quadruped' else 0
render_kwargs = {'height': 84, 'width': 84, 'camera_id': camera_id}
env = pixels.Wrapper(env,
pixels_only=False,
render_kwargs=render_kwargs)
env = FrameStackWrapper(env, frame_stack)
action_spec = env.action_spec()
assert np.all(action_spec.minimum >= -1.0)
assert np.all(action_spec.maximum <= +1.0)
return env | 0.747063 | 0.281952 |