text
stringlengths
0
1.05M
meta
dict
# 1 # digit.each { |row| row[1, 1] = row[1, 1] * scale } # digit.each do |row| # if row =~ /\|/ # scale.times { puts row } # else # puts row # end # end # 2 # class LCD # attr_accessor( :size, :spacing ) # # # # This hash is used to define the segment display for the # # given digit. Each entry in the array is associated with # # the following states: # # # # HORIZONTAL # # VERTICAL # # HORIZONTAL # # VERTICAL # # HORIZONTAL # # DONE # # # # The HORIZONTAL state produces a single horizontal line. There # # are two types: # # # # 0 - skip, no line necessary, just space fill # # 1 - line required of given size # # # # The VERTICAL state produces a either a single right side line, # # a single left side line or a both lines. # # # # 0 - skip, no line necessary, just space fill # # 1 - single right side line # # 2 - single left side line # # 3 - both lines # # # # The DONE state terminates the state machine. This is not needed # # as part of the data array. # # # @@lcdDisplayData = { # "0" => [ 1, 3, 0, 3, 1 ], # "1" => [ 0, 1, 0, 1, 0 ], # "2" => [ 1, 1, 1, 2, 1 ], # "3" => [ 1, 1, 1, 1, 1 ], # "4" => [ 0, 3, 1, 1, 0 ], # "5" => [ 1, 2, 1, 1, 1 ], # "6" => [ 1, 2, 1, 3, 1 ], # "7" => [ 1, 1, 0, 1, 0 ], # "8" => [ 1, 3, 1, 3, 1 ], # "9" => [ 1, 3, 1, 1, 1 ] # } # @@lcdStates = [ # "HORIZONTAL", # "VERTICAL", # "HORIZONTAL", # "VERTICAL", # "HORIZONTAL", # "DONE" # ] # def initialize( size=1, spacing=1 ) # @size = size # @spacing = spacing # end # def display( digits ) # states = @@lcdStates.reverse # 0.upto(@@lcdStates.length) do |i| # case states.pop # when "HORIZONTAL" # line = "" # digits.each_byte do |b| # line += horizontal_segment( # @@lcdDisplayData[b.chr][i] # ) # end # print line + "\n" # when "VERTICAL" # 1.upto(@size) do |j| # line = "" # digits.each_byte do |b| # line += vertical_segment( # @@lcdDisplayData[b.chr][i] # ) # end # print line + "\n" # end # when "DONE" # break # end # end # end # def horizontal_segment( type ) # case type # when 1 # return " " + ("-" * @size) + " " + (" " * @spacing) # else # return " " + (" " * @size) + " " + (" " * @spacing) # end # end # def vertical_segment( type ) # case type # when 1 # return " " + (" " * @size) + "|" + (" " * @spacing) # when 2 # return "|" + (" " * @size) + " " + (" " * @spacing) # when 3 # return "|" + (" " * @size) + "|" + (" " * @spacing) # else # return " " + (" " * @size) + " " + (" " * @spacing) # end # end # end # from sys import argv # script, vert_line, hori_line = argv # vert = "-" # hori = "|" # space = "" # def ascii(vert, hori, space): # new = space.replace(""," ") # return ascii # ascii(vert, hori, space) # var1 = ascii("-", "|", "") # print "%s%s%s%s%s%s%s%s%s" % (space, (vert*2), (space*8), (vert*2), (space*3), (vert*2), (space*8), (vert*2), space) # from sys import argv # script, zero, ascii_one, ascii_two, ascii_three, ascii_four, ascii_five = argv # zero = {""" def line1(): print " -- -- -- --" return line1 def line2(): print "| | | | | | | |" return line2 def line3(): print "| | | | | | | |" return line3 def line4(): print " -- -- -- --" return line4 def line5(): print "| | | | | | | " return line5 def line6(): print "| | | | | | |" return line6 def line7(): print " -- -- -- --" return line7 print "%s%s%s%s%s%s%s" % (line1(), line2(), line3(), line4(), line5(), line6(), line7()) # print line1(), line2(), line3(), line4(), line5(), line6(), line7() # S H O U L D P R I N T # print """ # -- -- -- -- # | | | | | | | | # | | | | | | | | # -- -- -- -- # | | | | | | | # | | | | | | | # -- -- -- -- # """
{ "repo_name": "chrisortman/CIS-121", "path": "k0459866/Extra_Credit/extra_credit01.py", "copies": "1", "size": "4703", "license": "mit", "hash": -2118607783031687400, "line_mean": 25.5706214689, "line_max": 118, "alpha_frac": 0.391877525, "autogenerated": false, "ratio": 2.9879288437102924, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.38798063687102924, "avg_score": null, "num_lines": null }
## 1. Neural networks and iris flowers ## import pandas import matplotlib.pyplot as plt import numpy as np # Read in dataset iris = pandas.read_csv("iris.csv") # shuffle rows shuffled_rows = np.random.permutation(iris.index) iris = iris.loc[shuffled_rows,:] print(iris.head()) # There are 2 species print(iris.species.unique()) iris.hist() plt.show() ## 2. Neurons ## z = np.asarray([[9, 5, 4]]) y = np.asarray([[-1, 2, 4]]) # np.dot is used for matrix multiplication # z is 1x3 and y is 1x3, z * y.T is then 1x1 print(np.dot(z,y.T)) # Variables to test sigmoid_activation iris["ones"] = np.ones(iris.shape[0]) X = iris[['ones', 'sepal_length', 'sepal_width', 'petal_length', 'petal_width']].values y = (iris.species == 'Iris-versicolor').values.astype(int) # The first observation x0 = X[0] # Initialize thetas randomly theta_init = np.random.normal(0,0.01,size=(5,1)) def sigmoid_activation(x,theta): return 1/ (1+ np.exp(-np.dot(theta.T , x))) a1 = sigmoid_activation(x0,theta_init) ## 3. Cost function ## # First observation's features and target x0 = X[0] y0 = y[0] # Initialize parameters, we have 5 units and just 1 layer theta_init = np.random.normal(0,0.01,size=(5,1)) def singlecost(X,y,theta): h = 1/ (1+ np.exp(-np.dot(theta.T,X))) return -np.mean(y * np.log(h) + (1-y) * np.log(1-h)) first_cost = singlecost(x0,y0,theta_init) ## 4. Compute the Gradients ## # Initialize parameters theta_init = np.random.normal(0,0.01,size=(5,1)) # Store the updates into this array grads = np.zeros(theta_init.shape) # Number of observations n = X.shape[0] for j, obs in enumerate(X): # Compute activation h = sigmoid_activation(obs, theta_init) # Get delta delta = (y[j]-h) * h * (1-h) * obs # accumulate grads += delta[:,np.newaxis]/X.shape[0] ## 5. Two layer network ## theta_init = np.random.normal(0,0.01,size=(5,1)) # set a learning rate learning_rate = 0.1 # maximum number of iterations for gradient descent maxepochs = 10000 # costs convergence threshold, ie. (prevcost - cost) > convergence_thres convergence_thres = 0.0001 def learn(X, y, theta, learning_rate, maxepochs, convergence_thres): costs = [] cost = singlecost(X, y, theta) # compute initial cost costprev = cost + convergence_thres + 0.01 # set an inital costprev to past while loop counter = 0 # add a counter # Loop through until convergence for counter in range(maxepochs): grads = np.zeros(theta.shape) for j, obs in enumerate(X): h = sigmoid_activation(obs, theta) # Compute activation delta = (y[j]-h) * h * (1-h) * obs # Get delta grads += delta[:,np.newaxis]/X.shape[0] # accumulate # update parameters theta += grads * learning_rate counter += 1 # count costprev = cost # store prev cost cost = singlecost(X, y, theta) # compute new cost costs.append(cost) if np.abs(costprev-cost) < convergence_thres: break plt.plot(costs) plt.title("Convergence of the Cost Function") plt.ylabel("J($\Theta$)") plt.xlabel("Iteration") plt.show() return theta theta = learn(X, y, theta_init, learning_rate, maxepochs, convergence_thres) ## 6. Neural Network ## theta0_init = np.random.normal(0,0.01,size=(5,4)) theta1_init = np.random.normal(0,0.01,size=(5,1)) def feedforward(X, theta0, theta1): # feedforward to the first layer a1 = sigmoid_activation(X.T, theta0).T # add a column of ones for bias term a1 = np.column_stack([np.ones(a1.shape[0]), a1]) # activation units are then inputted to the output layer out = sigmoid_activation(a1.T, theta1) return out h = feedforward(X, theta0_init, theta1_init) ## 7. Multiple neural network cost function ## theta0_init = np.random.normal(0,0.01,size=(5,4)) theta1_init = np.random.normal(0,0.01,size=(5,1)) # X and y are in memory and should be used as inputs to multiplecost() def multiplecost(X, y,theta0_init, theta1_init): return -np.mean((y * np.log(h)) + (1-y) * np.log(1-h)) c = multiplecost(X,y,theta0_init, theta1_init) ## 8. Backpropagation ## # Use a class for this model, it's good practice and condenses the code class NNet3: def __init__(self, learning_rate=0.5, maxepochs=1e4, convergence_thres=1e-5, hidden_layer=4): self.learning_rate = learning_rate self.maxepochs = int(maxepochs) self.convergence_thres = 1e-5 self.hidden_layer = int(hidden_layer) def _multiplecost(self, X, y): # feed through network l1, l2 = self._feedforward(X) # compute error inner = y * np.log(l2) + (1-y) * np.log(1-l2) # negative of average error return -np.mean(inner) def _feedforward(self, X): # feedforward to the first layer l1 = sigmoid_activation(X.T, self.theta0).T # add a column of ones for bias term l1 = np.column_stack([np.ones(l1.shape[0]), l1]) # activation units are then inputted to the output layer l2 = sigmoid_activation(l1.T, self.theta1) return l1, l2 def predict(self, X): _, y = self._feedforward(X) return y def learn(self, X, y): nobs, ncols = X.shape self.theta0 = np.random.normal(0,0.01,size=(ncols,self.hidden_layer)) self.theta1 = np.random.normal(0,0.01,size=(self.hidden_layer+1,1)) self.costs = [] cost = self._multiplecost(X, y) self.costs.append(cost) costprev = cost + self.convergence_thres+1 # set an inital costprev to past while loop counter = 0 # intialize a counter # Loop through until convergence for counter in range(self.maxepochs): # feedforward through network l1, l2 = self._feedforward(X) # Start Backpropagation # Compute gradients l2_delta = (y-l2) * l2 * (1-l2) l1_delta = l2_delta.T.dot(self.theta1.T) * l1 * (1-l1) # Update parameters by averaging gradients and multiplying by the learning rate self.theta1 += l1.T.dot(l2_delta.T) / nobs * self.learning_rate self.theta0 += X.T.dot(l1_delta)[:,1:] / nobs * self.learning_rate # Store costs and check for convergence counter += 1 # Count costprev = cost # Store prev cost cost = self._multiplecost(X, y) # get next cost self.costs.append(cost) if np.abs(costprev-cost) < self.convergence_thres and counter > 500: break # Set a learning rate learning_rate = 0.5 # Maximum number of iterations for gradient descent maxepochs = 10000 # Costs convergence threshold, ie. (prevcost - cost) > convergence_thres convergence_thres = 0.00001 # Number of hidden units hidden_units = 4 # Initialize model model = NNet3(learning_rate=learning_rate, maxepochs=maxepochs, convergence_thres=convergence_thres, hidden_layer=hidden_units) # Train model model.learn(X, y) # Plot costs plt.plot(model.costs) plt.title("Convergence of the Cost Function") plt.ylabel("J($\Theta$)") plt.xlabel("Iteration") plt.show() ## 9. Splitting data ## # First 70 rows to X_train and y_train # Last 30 rows to X_train and y_train X_train = X[0:70] y_train = y[0:70] X_test = X[70:len(X)] y_test = y[70:len(y)] ## 10. Predicting iris flowers ## from sklearn.metrics import roc_auc_score # Set a learning rate learning_rate = 0.5 # Maximum number of iterations for gradient descent maxepochs = 10000 # Costs convergence threshold, ie. (prevcost - cost) > convergence_thres convergence_thres = 0.00001 # Number of hidden units hidden_units = 4 # Initialize model model = NNet3(learning_rate=learning_rate, maxepochs=maxepochs, convergence_thres=convergence_thres, hidden_layer=hidden_units) model.learn(X_train,y_train) x = model.predict(X_test)[0] auc = roc_auc_score(y_test, x)
{ "repo_name": "vipmunot/Data-Analysis-using-Python", "path": "Machine learning Intermediate/Introduction to neural networks-121.py", "copies": "1", "size": "8043", "license": "mit", "hash": -224951887183269150, "line_mean": 29.7022900763, "line_max": 97, "alpha_frac": 0.6374487132, "autogenerated": false, "ratio": 3.1162340178225496, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42536827310225495, "avg_score": null, "num_lines": null }
#1 # foo = None # print (foo) # print ("test {}.".format(foo)) # foo = 1.0 # print (foo) # print ("test {}.".format(foo)) # print ("test __str__() {}.".format(foo.__str__())) import osisoftpy # main package import time import dateutil.parser import datetime import pytz import json # webapi = osisoftpy.webapi('https://dev.dstcontrols.com/piwebapi') # elements = webapi.elements(query='attributename:PythonAFInserted AND name:Attributes') # element = elements[0] # print element # att = element['PythonAFInserted'] # att.update_value('11/22/2017 3PM', 12321) # webapi = osisoftpy.webapi('https://gold.dstcontrols.local/piwebapi', authtype='basic', username='ak-piwebapi-svc@dstcontrols.local', password='DP$28GhMyp*!E&gc') webapi = osisoftpy.webapi('https://dev.dstcontrols.com/piwebapi') # points = webapi.points(query='name:SINU*') points = webapi.points(query='name:s* OR name:a* OR name:r* OR name: CD*') # for x in range(0,400): # points.pop() # def callback_current(sender): # #sender is Point object # print('Current Value of {} changed to {} at {}'.format( # sender.name, sender.current_value.value, # sender.current_value.timestamp)) # First parameter is websocket object required by library # Second parameter is message response as string def parse_message(ws, message): j = json.loads(message) for point in j['Items']: for value in point['Items']: print('Point: {}, New Value: {}, Timestamp: {}, Current Time: {}'. format(point['Name'], value['Value'], str(dateutil.parser.parse(str( value['Timestamp'])))[:19], datetime.datetime.fromtimestamp( time.time()).strftime('%Y-%m-%d %H:%M:%S'))) # def callback_channel(ws, message): # j = json.loads(message) # for point in j['Items']: # for value in point['Items']: # print('Point: {}, New Value: {}, Timestamp: {}'.format( # point['Name'], value['Value'], value['Timestamp'])) # def callback_current(sender): # if isinstance(sender.current_value.value, dict) == False: # value = sender.current_value.value # elif sender.current_value.value.get('IsSystem') == False: # value = str(sender.current_value.value.get('Value')) # else: # value = str(sender.current_value.value.get('Name')) # print('Tag: {}, DateTime: {}, Value: {}'.format( # sender.name, # str(dateutil.parser.parse(str(sender.current_value.timestamp)))[:19], # value)) # str(dateutil.parser.parse(str(sender.current_value.timestamp)).astimezone(PST))[:19] # df = df.append( # { # 'tag name': # sender.name, # 'DateTime': # str(dateutil.parser.parse(str( # sender.current_value.timestamp)))[:19], # 'Pressure': # value # }, # ignore_index=True) points.start_channel(parse_message) print('start') while True: time.sleep(10) print('Time passed') # point.update_value('2000-01-01T07:00:00Z', 53) # end_value = point.end() # timestamp = end_value.timestamp # value = end_value.value # print('{}: {}'.format(timestamp, value)) # summary_values = point.summary(summarytype='Total', starttime='*-1w', endtime='*', summaryduration='1d') # for summary_value in summary_values: # calculationtype = summary_value.calculationtype # timestamp = summary_value.timestamp # value = summary_value.value # print('{} is {} starting at {}'.format(calculationtype, value, timestamp)) # def callback_current(sender): # print('CALLBACK: Current Value of {} changed to {} at {}'.format(sender.name, sender.current_value.value, sender.current_value.timestamp)) # def callback_end(sender): # print('CALLBACK: End Value of {} changed to {} at {}'.format(sender.name, sender.end_value.value, sender.end_value.timestamp)) # webapi.subscribe(points, 'current', callback=callback_current) # webapi.subscribe(points, 'end', callback=callback_end) # for point in points: # point.current() # time.sleep(30) # for point in points: # point.current() # interpolated_values_at_times = point.interpolatedattimes(['2017-01-01T00:00:00Z','2017-05-03T00:00:00Z']) # print('Number of Values for {}: {}'.format(point.name, interpolated_values_at_times.__len__())) # for interpolated_value in interpolated_values_at_times: # timestamp = interpolated_value.timestamp # value = interpolated_value.value # print('{}: {}'.format(timestamp, value)) # print(len(points)) # def callback(sender): # print('Callback {} {}'.format(sender.name, sender.current_value.value)) # webapi.subscribe(points, 'current', callback=callback) # points.current() # # print('Point: {} has inital value {} at {}'.format(point.name, value.value, value.timestamp)) # time.sleep(30) # points.current() # points = 0 # points = webapi.points(query='name:EdwinPythonTest') # for point in points: # print(point) # point = points[0] # ts = point.current().timestamp # y = time.strptime(ts, '%Y-%m-%dT%H:%M:%SZ') # localFormat = "%Y-%m-%d %H:%M" # localmoment_naive = datetime.strptime('2013-09-06 14:05', localFormat) # localtimezone = pytz.timezone('America/Los_Angeles') # localmoment = localtimezone.localize(localmoment_naive, is_dst=None) # utcmoment = localmoment.astimezone(pytz.utc) # print(utcmoment) # print(len(points)) # points = webapi.points(query='name:EdwinPythonTest') # print(len(points)) #3 # string = '2017-02-01 06:00' # print(string) # x = time.strptime(string, '%Y-%m-%d %H:%M') # print(x) # # times = ['2017-02-01 06:00', '2017-03-05 15:00', '2017-04-15 17:00'] # for t in times: # s = time.strptime(t, '%Y-%m-%d %H:%M') # print(s) # print(time.strftime('%Y-%m-%dT%H:%M:%SZ', s)) # ##
{ "repo_name": "dstcontrols/osisoftpy", "path": "examples/test.py", "copies": "1", "size": "5820", "license": "apache-2.0", "hash": 5977455616298648000, "line_mean": 31.1602209945, "line_max": 163, "alpha_frac": 0.6383161512, "autogenerated": false, "ratio": 3.1716621253405997, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43099782765406, "avg_score": null, "num_lines": null }
# 1. from merlin import Merlin engine = Merlin( company = 'my_company', environment = 'prod', instance = 'my_instance' ) # 2. from merlin.search import Search with engine(Search(q="dress")) as results: print results # 3. A query where we want 50 results starting from the 100th result s = Search(q="red dress", start=100, num=50) with engine(s) as results: print results # 4. A query where we only want back the "id" and "title" fields s = Search(q="red dress", fields=["id", "title"]) with engine(s) as results: print results # 5. Get all fields including debug fields s = Search(q='red dress', fields=['[debug]']) with engine(s) as results: print results # 6. from merlin.sort import Sort as S s = Search(q='red dress', sort=S.asc('price')) with engine(s) as results: print results # 7. s = Search(q='red dress', sort = [S.asc('price'), S.desc('size')]) with engine(s) as results: print results # 8. from merlin.filter import NF, Field s = Search( q = 'red dress', filter = NF.cnf( Field('price') < 100 ) ) with engine(s) as results: print results # 9. s = Search( q = "red dress", filter = NF.cnf( (Field('size') == ('S', 'M')) & (Field('price') < 100) ) ) with engine(s) as results: print results # 10. A query where we want red dresses in size 'S' or in size 'M' and # tag it as 'smallormedium' s = Search( q = "red dress", filter = NF.cnf( (Field("size") == ('S', 'M')), tag="smallormedium" ) ) with engine(s) as results: print results # 11. A query where we want red dresses under $100 # and the top 5 brands returned as facets from merlin.facet import Facet as F s = Search( q = 'red dress', filter = NF.cnf(Field('price') < 100), facet = F.enum('brand', num=5) ) with engine(s) as results: print results.facets.enums # 12. A query where we want red dresses and the range of prices returned s = Search( q = 'red dress', facets = F.range('price') ) with engine(s) as results: print results.facets.ranges # 13. A query where we want red dresses and a histogram of their # price fields from 0-500 in increments of 100. s = Search( q = 'red dress', facets = F.hist('price', start=0, end=500, gap=100) ) with engine(s) as results: print results.facets.histograms # 14. A search with multiple keyed facets on the 'brand' field s = Search( q = 'red dress', facets = [ F.range('price', tag="price_range"), F.hist('price', start=0, end=500, gap=100, tag='price_hist') ] ) with engine(s) as results: print results.facets # 15. pass array of tags to exclude into the facet s = Search( q = "red dress", facets = [ F.enum("brand", num=200, exclude=["tag1", "tag2"]) ] ) # 16. search for 'red dress' with spelling correction turned off S = Search(q="red dress", correct=False)
{ "repo_name": "blackbirdtech/merlin-python", "path": "examples/examples.py", "copies": "1", "size": "2957", "license": "apache-2.0", "hash": -1665897848235380700, "line_mean": 21.0671641791, "line_max": 72, "alpha_frac": 0.6168413933, "autogenerated": false, "ratio": 3.032820512820513, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.41496619061205126, "avg_score": null, "num_lines": null }
class Molecule(): def parse(self,argv): return parse_molecule(argv) class MoleculeNew(Molecule): def parse(self,argv): Dic = super().parse(argv) # print(Dic) total = 0 for num in Dic.values(): total+=int(num) percentDic = {} for e in Dic: # print(Dic[e]) percentDic.update({e:'{0:.2f} %'.format(int(Dic[e])/total * 100)}) return percentDic #### 3 #### ''' '[Co(H2NCH2CH2NH2)3]Cl3' 'K4[ON(SO3)2]2' 'Ka4[ON(SO3)2]2' 'K4[ON(SO3)' '''
{ "repo_name": "YenCChien/sss", "path": "PythonTest1.py", "copies": "1", "size": "3862", "license": "mpl-2.0", "hash": -8142365641684140000, "line_mean": 36.862745098, "line_max": 139, "alpha_frac": 0.5590367685, "autogenerated": false, "ratio": 2.954858454475899, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8923363504213939, "avg_score": 0.01810634375239194, "num_lines": 102 }
# 1 --------- # A simple test of the basic_aep model from fusedwind.plant_flow.basic_aep import aep_weibull_assembly import numpy as np aep = aep_weibull_assembly() # 1 --------- # 2 --------- # Set input parameters aep.wind_curve = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, \ 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0]) aep.power_curve = np.array([0.0, 0.0, 0.0, 187.0, 350.0, 658.30, 1087.4, 1658.3, 2391.5, 3307.0, 4415.70, \ 5000.0, 5000.0, 5000.0, 5000.0, 5000.0, 5000.0, 5000.0, 5000.0, 5000.0, 5000.0, 5000.0, 5000.0, \ 5000.0, 5000.0, 0.0]) aep.A = 8.35 aep.k = 2.15 aep.array_losses = 0.059 aep.other_losses = 0.0 aep.availability = 0.94 aep.turbine_number = 100 # 2 --------- # 3 --------- aep.run() # 3 --------- # 4 --------- print "Annual energy production for an offshore wind plant with 100 NREL 5 MW reference turbines." print "AEP gross output (before losses): {0:.1f} kWh".format(aep.gross_aep) print "AEP net output (after losses): {0:.1f} kWh".format(aep.net_aep) print # 4 ----------
{ "repo_name": "FUSED-Wind/fusedwind", "path": "docs/examples/Fused_flow_docs_example.py", "copies": "2", "size": "1168", "license": "apache-2.0", "hash": -3791004480347205000, "line_mean": 28.2, "line_max": 123, "alpha_frac": 0.5556506849, "autogenerated": false, "ratio": 2.3037475345167655, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8839288520274808, "avg_score": 0.004021939828391441, "num_lines": 40 }
"""1 Revision ID: 275df1efccf Revises: None Create Date: 2014-03-28 19:37:49.676179 """ # revision identifiers, used by Alembic. revision = '275df1efccf' down_revision = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('projects', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=60), nullable=True), sa.Column('description', sa.Text(), nullable=True), sa.Column('subject', sa.String(length=60), nullable=True), sa.Column('help_wanted', sa.String(length=140), nullable=True), sa.Column('timestamp', sa.DateTime(), nullable=True), sa.Column('schools', sa.String(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index('ix_projects_timestamp', 'projects', ['timestamp'], unique=False) op.create_table('roles', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=64), nullable=True), sa.Column('default', sa.Boolean(), nullable=True), sa.Column('permissions', sa.Integer(), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name') ) op.create_index('ix_roles_default', 'roles', ['default'], unique=False) op.create_table('users', sa.Column('id', sa.Integer(), nullable=False), sa.Column('email', sa.String(length=64), nullable=True), sa.Column('username', sa.String(length=64), nullable=True), sa.Column('role_id', sa.Integer(), nullable=True), sa.Column('new_role', sa.String(), nullable=True), sa.Column('password_hash', sa.String(length=128), nullable=True), sa.Column('confirmed', sa.Boolean(), nullable=True), sa.Column('name', sa.String(length=64), nullable=True), sa.Column('location', sa.String(length=64), nullable=True), sa.Column('about_me', sa.Text(), nullable=True), sa.Column('member_since', sa.DateTime(), nullable=True), sa.Column('last_seen', sa.DateTime(), nullable=True), sa.Column('avatar_hash', sa.String(length=32), nullable=True), sa.Column('milestones_completed', sa.Integer(), nullable=True), sa.Column('school', sa.String(length=100), nullable=True), sa.Column('teacher_email', sa.String(length=100), nullable=True), sa.Column('mentee_milestones_completed', sa.Integer(), nullable=True), sa.Column('interests', sa.String(length=100), nullable=True), sa.Column('expertise', sa.String(length=100), nullable=True), sa.Column('linkedin_id', sa.String(length=100), nullable=True), sa.Column('participate', sa.Boolean(), nullable=True), sa.ForeignKeyConstraint(['role_id'], ['roles.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index('ix_users_email', 'users', ['email'], unique=True) op.create_index('ix_users_username', 'users', ['username'], unique=True) op.create_table('kid_parent_association_table', sa.Column('parent_id', sa.Integer(), nullable=False), sa.Column('kid_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['kid_id'], ['users.id'], ), sa.ForeignKeyConstraint(['parent_id'], ['users.id'], ), sa.PrimaryKeyConstraint('parent_id', 'kid_id') ) op.create_table('teacher_to_project', sa.Column('teacher_id', sa.Integer(), nullable=True), sa.Column('project_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['project_id'], ['projects.id'], ), sa.ForeignKeyConstraint(['teacher_id'], ['users.id'], ) ) op.create_table('MentorProjectAssociation', sa.Column('mentor_id', sa.Integer(), nullable=True), sa.Column('project_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['mentor_id'], ['users.id'], ), sa.ForeignKeyConstraint(['project_id'], ['projects.id'], ) ) op.create_table('StudentProjectAssociation', sa.Column('student_id', sa.Integer(), nullable=True), sa.Column('project_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['project_id'], ['projects.id'], ), sa.ForeignKeyConstraint(['student_id'], ['users.id'], ) ) op.create_table('follows', sa.Column('follower_id', sa.Integer(), nullable=False), sa.Column('followed_id', sa.Integer(), nullable=False), sa.Column('timestamp', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['followed_id'], ['users.id'], ), sa.ForeignKeyConstraint(['follower_id'], ['users.id'], ), sa.PrimaryKeyConstraint('follower_id', 'followed_id') ) op.create_table('posts', sa.Column('id', sa.Integer(), nullable=False), sa.Column('body', sa.Text(), nullable=True), sa.Column('body_html', sa.Text(), nullable=True), sa.Column('timestamp', sa.DateTime(), nullable=True), sa.Column('author_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['author_id'], ['users.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index('ix_posts_timestamp', 'posts', ['timestamp'], unique=False) op.create_table('comments', sa.Column('id', sa.Integer(), nullable=False), sa.Column('body', sa.Text(), nullable=True), sa.Column('body_html', sa.Text(), nullable=True), sa.Column('timestamp', sa.DateTime(), nullable=True), sa.Column('disabled', sa.Boolean(), nullable=True), sa.Column('author_id', sa.Integer(), nullable=True), sa.Column('post_id', sa.Integer(), nullable=True), sa.Column('project_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['author_id'], ['users.id'], ), sa.ForeignKeyConstraint(['post_id'], ['posts.id'], ), sa.ForeignKeyConstraint(['project_id'], ['projects.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index('ix_comments_timestamp', 'comments', ['timestamp'], unique=False) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_index('ix_comments_timestamp', 'comments') op.drop_table('comments') op.drop_index('ix_posts_timestamp', 'posts') op.drop_table('posts') op.drop_table('follows') op.drop_table('StudentProjectAssociation') op.drop_table('MentorProjectAssociation') op.drop_table('teacher_to_project') op.drop_table('kid_parent_association_table') op.drop_index('ix_users_username', 'users') op.drop_index('ix_users_email', 'users') op.drop_table('users') op.drop_index('ix_roles_default', 'roles') op.drop_table('roles') op.drop_index('ix_projects_timestamp', 'projects') op.drop_table('projects') ### end Alembic commands ###
{ "repo_name": "SuperQuest/v1", "path": "migrations/versions/275df1efccf_1.py", "copies": "1", "size": "6532", "license": "mit", "hash": -4899360255028525000, "line_mean": 44.0482758621, "line_max": 85, "alpha_frac": 0.6576852419, "autogenerated": false, "ratio": 3.437894736842105, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9539619738478209, "avg_score": 0.011192048052779329, "num_lines": 145 }
# 1. print_log('\n1. Creates a new local pool ledger configuration that is used ' 'later when connecting to ledger.\n') pool_config = json.dumps({'genesis_txn': genesis_file_path}) try: await pool.create_pool_ledger_config(pool_name, pool_config) except IndyError: await pool.delete_pool_ledger_config(config_name=pool_name) await pool.create_pool_ledger_config(pool_name, pool_config) # 2. print_log('\n2. Open pool ledger and get handle from libindy\n') pool_handle = await pool.open_pool_ledger(config_name=pool_name, config=None) # 3. print_log('\n3. Creating new secure wallet\n') try: await wallet.create_wallet(wallet_config, wallet_credentials) except IndyError: await wallet.delete_wallet(wallet_config, wallet_credentials) await wallet.create_wallet(wallet_config, wallet_credentials) # 4. print_log('\n4. Open wallet and get handle from libindy\n') wallet_handle = await wallet.open_wallet(wallet_config, wallet_credentials) # 5. print_log('\n5. Generating and storing steward DID and verkey\n') steward_seed = '000000000000000000000000Steward1' did_json = json.dumps({'seed': steward_seed}) steward_did, steward_verkey = await did.create_and_store_my_did(wallet_handle, did_json) print_log('Steward DID: ', steward_did) print_log('Steward Verkey: ', steward_verkey) # 6. print_log('\n6. Generating and storing trust anchor DID and verkey\n') trust_anchor_did, trust_anchor_verkey = await did.create_and_store_my_did(wallet_handle, "{}") print_log('Trust anchor DID: ', trust_anchor_did) print_log('Trust anchor Verkey: ', trust_anchor_verkey) # 7. print_log('\n7. Building NYM request to add Trust Anchor to the ledger\n') nym_transaction_request = await ledger.build_nym_request(submitter_did=steward_did, target_did=trust_anchor_did, ver_key=trust_anchor_verkey, alias=None, role='TRUST_ANCHOR') print_log('NYM transaction request: ') pprint.pprint(json.loads(nym_transaction_request)) # 8. print_log('\n8. Sending NYM request to the ledger\n') nym_transaction_response = await ledger.sign_and_submit_request(pool_handle=pool_handle, wallet_handle=wallet_handle, submitter_did=steward_did, request_json=nym_transaction_request) print_log('NYM transaction response: ') pprint.pprint(json.loads(nym_transaction_response)) # 9. print_log('\n9. Build the SCHEMA request to add new schema to the ledger as a Steward\n') seq_no = 1 schema = { 'seqNo': seq_no, 'dest': steward_did, 'data': { 'id': '1', 'name': 'gvt', 'version': '1.0', 'ver': '1.0', 'attrNames': ['age', 'sex', 'height', 'name'] } } schema_data = schema['data'] print_log('Schema data: ') pprint.pprint(schema_data) print_log('Schema: ') pprint.pprint(schema) schema_request = await ledger.build_schema_request(steward_did, json.dumps(schema_data)) print_log('Schema request: ') pprint.pprint(json.loads(schema_request)) # 10. print_log('\n10. Sending the SCHEMA request to the ledger\n') schema_response = await ledger.sign_and_submit_request(pool_handle, wallet_handle, steward_did, schema_request) print_log('Schema response:') pprint.pprint(json.loads(schema_response)) # 11. print_log('\n11. Creating and storing CRED DEFINITION using anoncreds as Trust Anchor, for the given Schema\n') cred_def_tag = 'cred_def_tag' cred_def_type = 'CL' cred_def_config = json.dumps({"support_revocation": False}) (cred_def_id, cred_def_json) = await anoncreds.issuer_create_and_store_credential_def(wallet_handle, trust_anchor_did, json.dumps(schema_data), cred_def_tag, cred_def_type, cred_def_config) print_log('Credential definition: ') pprint.pprint(json.loads(cred_def_json))
{ "repo_name": "anastasia-tarasova/indy-sdk", "path": "docs/how-tos/issue-credential/python/step2.py", "copies": "2", "size": "4833", "license": "apache-2.0", "hash": -1418943095994416000, "line_mean": 48.3163265306, "line_max": 151, "alpha_frac": 0.5495551417, "autogenerated": false, "ratio": 3.9679802955665027, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0030508836342192196, "num_lines": 98 }
# 1. print_log('\n1. Creates Issuer wallet and opens it to get handle.\n') await wallet.create_wallet(pool_name, issuer_wallet_name, None, None, None) issuer_wallet_handle = await wallet.open_wallet(issuer_wallet_name, None, None) # 2. print_log('\n2. Creates Prover wallet and opens it to get handle.\n') await wallet.create_wallet(pool_name, prover_wallet_name, None, None, None) prover_wallet_handle = await wallet.open_wallet(prover_wallet_name, None, None) # 3. print_log('\n3. Issuer creates Claim Definition for Schema\n') schema = { 'seqNo': seq_no, 'dest': issuer_did, 'data': { 'name': 'gvt', 'version': '1.0', 'attr_names': ['age', 'sex', 'height', 'name'] } } schema_json = json.dumps(schema) schema_key = { 'name': schema['data']['name'], 'version': schema['data']['version'], 'did': schema['dest'], } claim_def_json = await anoncreds.issuer_create_and_store_claim_def(issuer_wallet_handle, issuer_did, schema_json, 'CL', False) print_log('Claim Definition: ') pprint.pprint(json.loads(claim_def_json)) # 4. print_log('\n4. Prover creates Link Secret\n') link_secret_name = 'link_secret' await anoncreds.prover_create_master_secret(prover_wallet_handle, link_secret_name) # 5. print_log('\n5. Issuer create Cred Offer\n') claim_offer_json = await anoncreds.issuer_create_claim_offer(issuer_wallet_handle, schema_json, issuer_did, prover_did) print_log('Claim Offer: ') pprint.pprint(json.loads(claim_offer_json)) # 6. print_log('\n6. Prover creates and stores Cred Request\n') claim_req_json = await anoncreds.prover_create_and_store_claim_req(prover_wallet_handle, prover_did, claim_offer_json, claim_def_json, link_secret_name) print_log('Claim Request: ') pprint.pprint(json.loads(claim_req_json)) # 7. print_log('\n7. Issuer creates Credential for received Cred Request\n') claim_json = json.dumps({ 'sex': ['male', '5944657099558967239210949258394887428692050081607692519917050011144233115103'], 'name': ['Alex', '1139481716457488690172217916278103335'], 'height': ['175', '175'], 'age': ['28', '28'] }) (_, claim_json) = await anoncreds.issuer_create_claim(issuer_wallet_handle, claim_req_json, claim_json, -1) # 8. print_log('\n8. Prover processes and stores received Credential\n') await anoncreds.prover_store_claim(prover_wallet_handle, claim_json, None)
{ "repo_name": "anastasia-tarasova/indy-sdk", "path": "docs/how-tos/negotiate-proof/python/step2.py", "copies": "2", "size": "2916", "license": "apache-2.0", "hash": -7977980992390937000, "line_mean": 39.5138888889, "line_max": 111, "alpha_frac": 0.5696159122, "autogenerated": false, "ratio": 3.5388349514563107, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.008892935674855261, "num_lines": 72 }
# 1. # Реализовать предобусловленный метод сопряженных градиентов для систем с матрицами Стилтьеса # с предобуславливанием по методам ILU(k), MILU(k) и ILU(k,e) # # (в последнем случае речь идёт об алгоритме ILU(k), в котором портрет матрицы заменён на множетсов пар индексов, # включающее пары равных индексов и пары индексов коэффициентов матрицы по модулю больших e); # # провести анализ скорости сходимости для заданной системы и подобрать приемлемые значения k. # # # стр. 90 – Метод сопряжённых градиентов # стр. 102 - Предобусловленный метод сопряженных градиентов # стр. 112 – Предобуславливание с использованием неполного LU-разложения # стр. 113 – определение матриц Стилтьеса # стр. 119 – определение ILU(k) разложения # стр. 120 – MILU-разложение # # Предобуславливание (также предобусловливание) — процесс преобразования условий задачи # для её более корректного численного решения. # # Предобуславливание обычно связано с уменьшением числа обусловленности задачи. # Предобуславливаемая задача обычно затем решается итерационным методом. # # https://ru.wikipedia.org/wiki/Метод_сопряжённых_градиентов # Метод сопряженных градиентов — метод нахождения локального экстреммума функции # на основе информации о её значениях и её градиенте. # # # # import numpy as np import math from typing import Tuple, Set import matplotlib.pyplot as plt import pickle from mod1.utils import MatrixBuilder, get_random_vector filename = "/Users/o2genum/Downloads/systems2.bin" def get_systems(): dense_number = 0 sparse_number = 200 # Try to read some already generated matrices try: with open(filename, 'rb') as input: system_set_dense, system_set_sparse = pickle.load(input) except FileNotFoundError: system_set_dense, system_set_sparse = [], [] if len(system_set_dense) == dense_number and len(system_set_sparse) == sparse_number: print("Got %d dense and %d sparse systems" % (len(system_set_dense), len(system_set_sparse))) return system_set_dense, system_set_sparse # Otherwise generate new matrices for i in range(0, dense_number): print('.', end='', flush=True) matrix = MatrixBuilder(4).stieltjes().nonsingular().gen() vector = get_random_vector(4) system_set_dense.append( (matrix, vector) ) for i in range(0, sparse_number): print('x', end='', flush=True) matrix = MatrixBuilder(9).sparse_stieltjes().nonsingular().gen() vector = get_random_vector(9) system_set_sparse.append( (matrix, vector) ) print('\n') # And save them for the next time with open(filename, 'wb') as output: pickle.dump([system_set_dense, system_set_sparse], output, pickle.HIGHEST_PROTOCOL) return system_set_dense, system_set_sparse def conj_grad(A: np.matrix, b: np.ndarray, x_0: np.ndarray): k = 0 r = {}; r[0] = b - A @ x_0 x = {}; x[0] = x_0 p = {} tau = {} mu = {} while not math.isclose(np.linalg.norm(r[k], ord=2), 0): k += 1 if k == 1: p[k] = r[0] else: tau[k-1] = (r[k-1].transpose() @ r[k-1]) / (r[k-2].transpose() @ r[k-2]) p[k] = r[k-1] + tau[k-1] * p[k-1] mu[k] = (r[k-1].transpose() @ r[k-1]) / (p[k].transpose() @ A @ p[k]) x[k] = x[k-1] + mu[k] * p[k] r[k] = r[k-1] - mu[k] * (A @ p[k]) if k > 300: raise ValueError("Does not converge") x_star = x[k] return x_star, k def lu_solve(L: np.matrix, R: np.matrix, b: np.array) -> np.array: y = np.zeros(b.size) for m in range(0, b.size): y[m] = b[m] - sum( L[m][i] * y[i] for i in range(0, m) ) y[m] /= L[m][m] x = np.zeros(b.size) for k in reversed(range(0, b.size)): x[k] = y[k] - sum( R[k][i] * x[i] for i in range(k + 1, b.size) ) x[k] /= R[k][k] return x def conj_grad_precond(A: np.matrix, b: np.ndarray, x_0: np.ndarray, precond_func): k = 0 r = {}; r[0] = b - A @ x_0 x = {}; x[0] = x_0 z = {} p = {} L, U = precond_func(A) z[0] = lu_solve(L, U, r[0]) while not math.isclose(np.linalg.norm(r[k], ord=2), 0): k += 1 if k == 1: p[k] = z[0] else: tau = (r[k-1].transpose() @ z[k-1]) / (r[k-2].transpose() @ z[k-2]) p[k] = z[k-1] + tau * p[k-1] mu = (r[k-1].transpose() @ z[k-1]) / (p[k].transpose() @ A @ p[k]) x[k] = x[k-1] + mu * p[k] r[k] = r[k-1] - mu * (A @ p[k]) z[k] = lu_solve(L, U, r[k]) if k > 300: raise ValueError("Does not converge") x_star = x[k] return x_star, k def matrix_portrait(A: np.matrix, e: float = None) -> Set[Tuple[int, int]]: if e is None: Omega = set() n = A.shape[0] for i in range(0, n): for j in range(0, n): if not math.isclose(A[i, j], 0): Omega.add((i, j)) return Omega else: Omega = set() n = A.shape[0] for i in range(0, n): for j in range(0, n): if abs(A[i, j]) > e or i==j: Omega.add((i, j)) return Omega def incomplete_lu(A: np.matrix, Omega: Set[Tuple[int, int]], modified: bool = False) -> Tuple[np.matrix, np.matrix]: A = A.copy() n = A.shape[0] L = np.eye(n, dtype=float) R = np.zeros(A.shape, dtype=float) for k in range(0, n): for i in range(k, n): if (k, i) in Omega: R[k, i] = A[k, i] elif modified: R[k, k] -= A[k, i] R[k, i] = 0 for j in range(k + 1, n): L[j, k] = A[j, k] / A[k, k] if (j, k) in Omega else 0 for p in range(k + 1, n): for q in range(k + 1, n): A[p, q] -= L[p, k]*R[k, q] return L, R def ilu_k(A: np.matrix, k: int, modified: bool = False, e: float = None) -> Tuple[np.matrix, np.matrix]: Omega = matrix_portrait(A, e) for i in range(0, k+1): L, R = incomplete_lu(A, Omega, modified) T = L @ R - A Omega |= matrix_portrait(T, e) # | is set union return L, R if __name__ == "__main__": np.set_printoptions(precision=4) dense_set, sparse_set = get_systems() test_set = sparse_set conv_mat_count = 0 for mat_i in range(0, len(test_set)): try: A = test_set[mat_i][0] b = test_set[mat_i][1] x_0 = np.array([0] * A.shape[0], dtype=float) x_star, k = conj_grad(A.copy(), b, x_0) #print("CONJ GRAD, iterations: " + str(k)) iter_n = 10 plainplot = [k] * iter_n iluplot = [] miluplot = [] for k in range(0, iter_n): #x_star, iters = conj_grad_precond(A.copy(), b, x_0, lambda A: ilu_k(A, 0, e=0.00000001*(10**k))) #print("PRECOND CONJ GRAD, iterations: " + str(iters)) #iluplot.append(iters) pass plt.plot(plainplot, color='g') #plt.plot(iluplot, color='b') conv_mat_count += 1 except ValueError as e: continue print("Conv matrices: " + str(conv_mat_count)) plt.show()
{ "repo_name": "maxmalysh/congenial-octo-adventure", "path": "mod2/task1.py", "copies": "1", "size": "8263", "license": "unlicense", "hash": -5245663431171793000, "line_mean": 29.3609958506, "line_max": 116, "alpha_frac": 0.5433921006, "autogenerated": false, "ratio": 2.316972767574414, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8347742002591414, "avg_score": 0.002524573116599855, "num_lines": 241 }
#1 #v 0.001 def _ERROR(Message,Function): import sys,traceback i=sys.exc_info();T=traceback.extract_tb(i[2])[0] print '-----' print 'Recall: '+Function print print 'File: '+T[0].split('\\')[-1]+', line '+str(T[1]) print "Code: '"+T[3]+"'" print traceback.format_exception_only(i[0], i[1])[0] print Message print '-----' #other errors should be thrown before this is reached global maxInstanceCount; maxInstanceCount = 1000000 def IncreaseRange(): #increase safety global maxInstanceCount; maxInstanceCount = 100000000 def DecreaseRange(): #increase speed global maxInstanceCount; maxInstanceCount = 10000 IWLDInstanceCount=0 def IWLD(Bool): #detect infinite while loop global IWLDInstanceCount,maxInstanceCount if not Bool: IWLDInstanceCount=0; maxInstanceCount=1000000; return False elif IWLDInstanceCount > maxInstanceCount: IWLDInstanceCount=0; maxInstanceCount=1000000; return False #stop while loop else: IWLDInstanceCount+=1; return True def ResetIWLD(): pass #will be removed IFLDInstanceCount=0 #detect infinite function loop def IFLD(): global IFLDInstanceCount def ResetIFLD(): global IFLDInstanceCount; IFLDInstanceCount=0
{ "repo_name": "Universal-Model-Converter/UMC3.0a", "path": "dev tests and files/data (scrapped dev5 attempt)/ERROR.py", "copies": "2", "size": "1218", "license": "mit", "hash": -6150143610555806000, "line_mean": 31.0526315789, "line_max": 84, "alpha_frac": 0.723316913, "autogenerated": false, "ratio": 3.460227272727273, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9962687720683836, "avg_score": 0.044171293008687426, "num_lines": 38 }
#1 #v 0.001 from ERROR import * from LOGGING import LOG as __LOG import COMMON """ - SetMatNode(): TODO ### these are extremely complicated and will take quite a while to solve (this means no color animations, ramps or special effects unachievable bt the shader alone) --- (a material must be active in a Mesh-type Object for this to take affect) - SetLight(): TODO ### I have to learn about these a little more :P """ #global public usage variables: global UMC_POINTS,UMC_LINES,UMC_LINESTRIP,UMC_LINELOOP,UMC_TRIANGLES,UMC_TRIANGLESTRIP,UMC_TRIANGLEFAN,UMC_QUADS,UMC_QUADSTRIP,UMC_POLYGON UMC_POINTS,UMC_LINES,UMC_LINESTRIP,UMC_LINELOOP,UMC_TRIANGLES,UMC_TRIANGLESTRIP,UMC_TRIANGLEFAN,UMC_QUADS,UMC_QUADSTRIP,UMC_POLYGON = range(10) #global defaults (bypassing re-definition from functions (speedup)) DLRS=[0.0,0.0,0.0, 0.0,0.0,0.0, 1.0,1.0,1.0] DM=[[1.0,0.0,0.0,0.0], [0.0,1.0,0.0,0.0], [0.0,0.0,1.0,0.0], [0.0,0.0,0.0,1.0]] #___________________________________________________________________________________________ import VIEWER #for interfacing with Libs #Active Data: ActiveScene = 0 ActiveObject = None ActiveMaterial = None ActiveTexture = None ActiveImage = None #for image pallets (TODO) ActivePrimitive = 0 #in active object def _Reset(): #called by VIEWER global ActiveScene,ActiveObject,ActiveMaterial,ActiveTexture,ActiveImage,ActivePrimitive ActiveScene = 0 ActiveObject = None ActiveMaterial = None ActiveTexture = None ActiveImage = None #for image pallets (TODO) ActivePrimitive = 0 #in active object def __GetOID(N): #check for specified object name/ID if type(N)==type(None): return '' if type(N)==int: return '' if N>len(VIEWER.Libs[3]) else N else: #N="Object1" for I,O in enumerate(VIEWER.Libs[3]): if O[0]==N: return I #break out of the loop return '' BoneLib = [] def __GetBID(S): #check for specified bone name/ID if type(S)==type(None): return '' global BoneLib if type(S)==int: return '' if S>len(BoneLib) else S else: #S="Bone1" for I,B in enumerate(BoneLib): if B[0]==S: return I #break out of the loop return '' def __GetMID(N): #check for specified material name/ID if type(N)==type(None): return '' if type(N)==int: return '' if N>len(VIEWER.Libs[4]) else N else: #N="Material1" for I,M in enumerate(VIEWER.Libs[4]): if M[0]==N: return I #break out of the loop return '' def __GetTID(N): #check for specified texture name/ID if type(N)==type(None): return '' if type(N)==int: return '' if N>len(VIEWER.Libs[6]) else N else: #N="Texture1" for I,T in enumerate(VIEWER.Libs[6]): if T[0]==N: return I #break out of the loop return '' def __GetIID(N): #check for specified image name/ID if type(N)==type(None): return '' if type(N)==int: return '' if N>len(VIEWER.Libs[7]) else N else: #N="Image1" for I,img in enumerate(VIEWER.Libs[7]): if img[0]==N: return I #break out of the loop return '' ''' hacks: (don't uncomment) def SetActiveScene(Scene = 0): global ActiveScene; ActiveScene = Scene def SetActiveObject(Object = None): global ActiveObject ActiveObject = __GetOID(Object) if ActiveObject=='': ActiveObject=None def SetActiveMaterial(Material = None): global ActiveMaterial ActiveMaterial = __GetMID(Material) if ActiveMaterial=='': ActiveMaterial=None def SetActiveTexture(Texture = None): global ActiveTexture; ActiveTexture = Texture def SetActiveImage(Image = None): global ActiveImage; ActiveImage = Image def SetActivePrimitive(Primitive = 0): global ActivePrimitive; ActivePrimitive = Primitive def GetActiveScene(): global ActiveScene; return ActiveScene def GetActiveObject(): global ActiveObject; return ActiveObject def GetActiveMaterial(): global ActiveMaterial; return ActiveMaterial def GetActiveTexture(): global ActiveTexture; return ActiveTexture def GetActiveImage(): global ActiveImage; return ActiveImage def GetActivePrimitive(): global ActivePrimitive; return ActivePrimitive ''' #___________________________________________________________________________________________ SceneCount = 0 #create a new scene, or activate the specified scene def SetScene( Name="Scene0" ): global SceneCount,ActiveScene if SceneCount==0: #change the default scene name VIEWER.Libs[2][0][0]=(Name if type(Name)==str else "Scene"+str(SceneCount)) SceneCount+=1 else: #user defined scenes already exist SceneIndex = None #TODO: usa a while loop for Index,Scene in enumerate(VIEWER.Libs[2]): #check for specified scene name/index if Scene[0]==Name or Index==Name: SceneIndex=Index if SceneIndex == None: #create a new scene VIEWER.Libs[2]+=[Name if type(Name)==str else "Scene"+str(SceneCount)] ActiveScene=len(VIEWER.Libs[2]) #set the active scene index to the newly added scene SceneCount+=1 else: ActiveScene=SceneIndex #set the active scene index to the specified scene __LOG('---FORMAT---: created Scene: %s'%Name) SetScene.func_defaults=( "Scene"+str(SceneCount), ) #TODO: #- active scene rename: SetScene( [('Name' or Index), "NewName"] ) #^this will rename the scene while setting it to active #___________________________________________________________________________________________ ObjectSceneID = [] #the indexed object's scene index #create a new object in the active scene, or activate and change the data in a specified object #(if a specified object exists in another scene, that object's scene will be set as active) def SetObject( Name="Object0", Viewport=0, LocRotSca=[], Sub_Name='', ParentName='' ): global ActiveScene,ActiveObject,ObjectSceneID,DLRS ObjectLib=VIEWER.Libs[3] #Verify Data: (use Defaults if neccesary) N = (ObjectLib[Name][0] if (type(Name)==int and Name>-1 and Name<(len(ObjectLib)+1) #get the name of the specified object ) else (Name if type(Name)==str else "Object"+str(len(ObjectLib)))) #N must be a string VP = (Viewport if (Viewport>0 and Viewport<25) else 1) #must be 1 to 24 LRS= (DLRS if len(LocRotSca)!=9 else LocRotSca) #TODO: advanced LRS verification SD = ["",(N if (Sub_Name=='' or type(Sub_Name)!=str) else Sub_Name),[],[]] P = (__GetOID(ParentName) if ParentName!=('__REMOVE__' or '') else ParentName) OID=__GetOID(N) if len(VIEWER.Libs[3])>0 else '' #try to get an active object index if OID=='': #if this is a new object: VIEWER.Libs[3].append([N,VP,LRS,SD,(P if len(VIEWER.Libs[3])>0 else '')]) #ignore parent index if this is the first object VIEWER.Libs[2][ActiveScene][1]+=[len(VIEWER.Libs[3])-1] ObjectSceneID+=[ActiveScene] ActiveObject=len(VIEWER.Libs[3])-1 __LOG('---FORMAT---: created Object: %s'%Name) else: #set the active object to the specicified object and change it's data ActiveObject,ActiveScene = OID,ObjectSceneID[OID]; AO=ObjectLib[OID] VIEWER.Libs[3][OID]=[ AO[0], #reset the object's data: ((VP if Viewport!=0 else AO[1]) if AO[1]!=VP else AO[1]), ((LRS if LRS!=DLRS else AO[2]) if AO[2]!=LRS else AO[2]), [AO[3][0],(AO[3][1] if Sub_Name=='' else SD[1]),AO[3][2],AO[3][3]], #reset sub data name (not data) ((P if ObjectLib[OID][4]!=P else ObjectLib[OID][4]) if P!='__REMOVE__' else '')] __LOG('---FORMAT---: re-set Object: %s'%VIEWER.Libs[3][OID][0]) SetObject.func_defaults=( "Object"+str(len(VIEWER.Libs[3])), 0, [], '', '' ) #TODO: #- verify the object doesn't have multiple parents (important) #- active object rename: SetObject( [('Name' or Index), "NewName"], ... ) #^this will rename the specified object while setting it active and editing it's data #___________________________________________________________________________________________ #set the active object's type to Rig and create a new bone within it, or change the data of an existing bone #(you will recieve an error if used on another Object type) #(you will also recieve an error if no object is defined) def SetBone( Name="Bone0", Viewport=0, LocRotSca=[], BindMtx=[], ParentName='', PreviousName='' ): global ActiveObject,BoneLib,N,VP,LRS,BM,PA,PR,DLRS BoneLib=VIEWER.Libs[3][ActiveObject][3][3] #Verify Data: (use Defaults if neccesary) N = (Name if type(Name)==str else "Bone"+str(len(BoneLib))) VP = (Viewport if (Viewport>0 and Viewport<25) else 1) LRS= (DLRS if len(LocRotSca)!=9 else LocRotSca) #TODO: advanced LRS verification BM = (DM if len(BindMtx)!=4 else BindMtx) #TODO: advanced matrix verification PA = (__GetBID(ParentName) if ParentName!=('__REMOVE__' or '') else '') PR = (__GetBID(PreviousName) if PreviousName!='' else '') def Set(): global ActiveObject,N,VP,LRS,BM,PA,PR,BoneLib #manage the bone data: BID= __GetBID(N) if len(BoneLib)>0 else '' #try to get an active object index if BID=='': VIEWER.Libs[3][ActiveObject][3][3]+=[[N,VP,LRS,BM,PA,PR]] #add a new bone __LOG('---FORMAT---: created Bone: %s'%Name) else: VIEWER.Libs[3][ActiveObject][3][3][BID]=[BoneLib[BID][0], #edit the specified bone ((VP if Viewport!=0 else BoneLib[BID][1]) if BoneLib[BID][1]!=VP else BoneLib[BID][1]), ((LRS if LRS!=DLRS else BoneLib[BID][2]) if BoneLib[BID][2]!=LRS else BoneLib[BID][2]), ((BM if BM!=DM44 else BoneLib[BID][3]) if BoneLib[BID][3]!=BM else BoneLib[BID][3]), ((PA if ParentName!='' else BoneLib[BID][4]) if BoneLib[BID][4]!=PA else BoneLib[BID][4]), ((PR if ParentName!='' else BoneLib[BID][5]) if BoneLib[BID][5]!=PR else BoneLib[BID][5])] #^- need to check for previous bone looping (in case of user error) __LOG('---FORMAT---: re-set Bone: %s'%BoneLib[BID][0]) #validate the active object if len(VIEWER.Libs[3])>0: if VIEWER.Libs[3][ActiveObject][3][0]=="": VIEWER.Libs[3][ActiveObject][3][0]="_Rig";Set() #set to "_Rig" and append a bone elif VIEWER.Libs[3][ActiveObject][3][0]=="_Rig": Set() #append a bone else: print 'Unable to append Bone to Object of type: "'+VIEWER.Libs[3][OID][3][0].split('_')[1]+'"\nignoring current data' else: print 'please define an object' SetBone.func_defaults=( "Bone"+str(len(VIEWER.Libs[3][ActiveObject][3][3])), 0, [], [], '', '' ) #TODO: #- instead of ignoring the invalid bone's data, create a new rig object to append it to #^you will then be able to parent the "ignored" bones to their proper object using a 3D editor #NOTE: only 1 object will be created to be the place-holder for the ignored bones (instead of 1 object for each ignored bone) #- rename bone: SetBone( [('Name' or Index), "NewName"], ... ) #^this will rename the specified bone while also editing it's data #___________________________________________________________________________________________ #set the active object's type to Mesh and append a primitive in it's data #(you will recieve an error if used on another Object type) #(you will also recieve an error if no object is defined) def SetPrimitive( Name=UMC_TRIANGLES ): global ActiveMaterial #TODO: figure out how to get the var itself to display (not it's value) if len(VIEWER.Libs[3])>0: #validate the active object if VIEWER.Libs[3][ActiveObject][3][0]=="": VIEWER.Libs[3][ActiveObject][3][0]="_Mesh" VIEWER.Libs[3][ActiveObject][3][3]=[[],[],[[],[]],[[],[],[],[],[],[],[],[]],[],[]] VIEWER.Libs[3][ActiveObject][3][3][5]+=[[Name,[]]] #set to "_Mesh" and append a primitive elif VIEWER.Libs[3][ActiveObject][3][0]=="_Mesh": VIEWER.Libs[3][ActiveObject][3][3][5]+=[[Name,[]]] #append a primitive else: #return error print 'Unable to append Primitive to Object of type: "'+VIEWER.Libs[3][OID][3][0].split('_')[1]+'"\nignoring current data' else: print 'please define an object' #''' ''' if ActiveMaterial!=None: if VIEWER.Libs[3][ActiveObject][3][2] != ActiveMaterial: VIEWER.Libs[3][ActiveObject][3][2] = ActiveMaterial #''' SetPrimitive.func_defaults=( Name, ) #TODO: #- index the proper primitive to add facepoints to #^(I personally havn't seen a format you'd need this option for, but the possibility of it still lies about) #___________________________________________________________________________________________ #set the active object's type to Mesh and append a valid Vector List to it's data #(you will recieve an error if used on another Object type) #(you will also recieve an error if no object is defined) def SetVerts( List=[] ): global ActiveObject if len(VIEWER.Libs[3])>0: if VIEWER.Libs[3][ActiveObject][3][0]=="": VIEWER.Libs[3][ActiveObject][3][0]="_Mesh" VIEWER.Libs[3][ActiveObject][3][3]=[List,[],[[],[]],[[],[],[],[],[],[],[],[]],[],[]] __LOG('---FORMAT---: set Vert List with %i verts'%len(List)) elif VIEWER.Libs[3][ActiveObject][3][0]=="_Mesh": VIEWER.Libs[3][ActiveObject][3][3][0]=List __LOG('---FORMAT---: set Vert List with %i verts'%len(List)) else: print 'Unable to append Vert List to Object of type: "'+VIEWER.Libs[3][OID][3][0].split('_')[1]+'"\nignoring current data' else: print 'please define an object' def SetNormals( List=[] ): global ActiveObject if len(VIEWER.Libs[3])>0: if VIEWER.Libs[3][ActiveObject][3][0]=="": VIEWER.Libs[3][ActiveObject][3][0]="_Mesh" VIEWER.Libs[3][ActiveObject][3][3]=[[],List,[[],[]],[[],[],[],[],[],[],[],[]],[],[]] __LOG('---FORMAT---: set Normal List with %i normals'%len(List)) elif VIEWER.Libs[3][ActiveObject][3][0]=="_Mesh": VIEWER.Libs[3][ActiveObject][3][3][1]=List __LOG('---FORMAT---: set Normal List with %i normals'%len(List)) else: print 'Unable to append Normal List to Object of type: "'+VIEWER.Libs[3][OID][3][0].split('_')[1]+'"\nignoring current data' else: print 'please define an object' def SetColors( List0=[], List1=[] ): global ActiveObject if len(VIEWER.Libs[3])>0: if VIEWER.Libs[3][ActiveObject][3][0]=="": VIEWER.Libs[3][ActiveObject][3][0]="_Mesh" VIEWER.Libs[3][ActiveObject][3][3]=[[],[],[List0,List1],[[],[],[],[],[],[],[],[]],[],[]] __LOG('---FORMAT---: set Color Lists with [%i,%i] colors'%(len(List0),len(List1))) elif VIEWER.Libs[3][ActiveObject][3][0]=="_Mesh": VIEWER.Libs[3][ActiveObject][3][3][2]=[List0,List1] __LOG('---FORMAT---: set Color Lists with [%i,%i] colors'%(len(List0),len(List1))) else: print 'Unable to append Color Lists to Object of type: "'+VIEWER.Libs[3][OID][3][0].split('_')[1]+'"\nignoring current data' else: print 'please define an object' def SetUVs( List0=[], List1=[], List2=[], List3=[], List4=[], List5=[], List6=[], List7=[] ): global ActiveObject if len(VIEWER.Libs[3])>0: if VIEWER.Libs[3][ActiveObject][3][0]=="": VIEWER.Libs[3][ActiveObject][3][0]="_Mesh" VIEWER.Libs[3][ActiveObject][3][3]=[[],[],[[],[]],[List0,List1,List2,List3,List4,List5,List6,List7],[],[]] __LOG('---FORMAT---: set UV Lists with [%i,%i,%i,%i,%i,%i,%i,%i] UVs'%( len(List0),len(List1),len(List2),len(List3),len(List4),len(List5),len(List6),len(List7))) elif VIEWER.Libs[3][ActiveObject][3][0]=="_Mesh": VIEWER.Libs[3][ActiveObject][3][3][0]=[List0,List1,List2,List3,List4,List5,List6,List7] __LOG('---FORMAT---: set UV Lists with [%i,%i,%i,%i,%i,%i,%i,%i] UVs'%( len(List0),len(List1),len(List2),len(List3),len(List4),len(List5),len(List6),len(List7))) else: print 'Unable to append UV Lists to Object of type: "'+VIEWER.Libs[3][OID][3][0].split('_')[1]+'"\nignoring current data' else: print 'please define an object' #TODO: #- validate vector lists #- Validate replacements (don't replace a data with a default unless specified) #___________________________________________________________________________________________ #Vectors: [ X, Y(, Z) ] #Colors: [R,G,B,A] int( 0 : 255 ) OR float( 0.0 : 1.0 ) #^be careful not to specify an int when your type is float (for colors) #^2D Verts and Normals are allowd. #append a facepoint to the active primitive with the specified vectors #(colors and uv's in list format are assumed to be single channel, and are read as such) def __Index(value,List,Type=''): #returns either a valid index or '' if type(value)==tuple: value=list(value) if type(value)==list: #[X,Y(,Z)] or [I/R(,A/G(,B(,A)))] try: return List.index(value) except: List+=[value] __LOG('---FORMAT---: set %s: %s'%(Type,str(value))) return List.index(value) #vector or color elif type(value)==int: return value #index (doesn't validate against len(list)) elif type(value)==str: return '' #no vector (validate any string to '') def SetFacepoint( Vert='', Normal='', Color='', UV='' ): global ActiveObject #verify we havn't switched objects to an invalid type before trying to add facepoints: if VIEWER.Libs[3][ActiveObject][3][0]=="_Mesh": #we can only set the facepoints of an active mesh object if len(VIEWER.Libs[3][ActiveObject][3][3])>0: #we can't append facepoints to an object with no primitives. Colors,UVs = VIEWER.Libs[3][ActiveObject][3][3][2],VIEWER.Libs[3][ActiveObject][3][3][3] VID = __Index(Vert,VIEWER.Libs[3][ActiveObject][3][3][0],'Vert') NID = __Index(Normal,VIEWER.Libs[3][ActiveObject][3][3][1],'Nornal') CIDs = ( (__Index(Color[0],Colors[0],'Color0') ,(__Index(Color[1],Colors[1],'Color1') if len(Color)==2 else '') ) if type(Color)==tuple else (__Index(Color,Colors[0]),'') ) UVIDs = ( (__Index(UV[0],UVs[0],'UV0') ,(__Index(UV[1],UVs[1],'UV1') if len(UV)>=2 else '') ,(__Index(UV[2],UVs[2],'UV2') if len(UV)>=3 else '') ,(__Index(UV[3],UVs[3],'UV3') if len(UV)>=4 else '') ,(__Index(UV[4],UVs[4],'UV4') if len(UV)>=5 else '') ,(__Index(UV[5],UVs[5],'UV5') if len(UV)>=6 else '') ,(__Index(UV[6],UVs[6],'UV6') if len(UV)>=7 else '') ,(__Index(UV[7],UVs[7],'UV7') if len(UV)==8 else '') ) if type(UV)==tuple else (__Index(UV,UVs[0]),'','','','','','','') ) VIEWER.Libs[3][ActiveObject][3][3][5][-1][1]+=[[VID,NID,CIDs,UVIDs]] __LOG('---FORMAT---: set Facepoint: [%s, %s, %s, %s]'%(str(VID),str(NID),str(CIDs),str(UVIDs))) else: print 'unable to append to a non-existant primitive' else: print 'Unable to append Facepoint to Object of type: "'+VIEWER.Libs[3][OID][3][0].split('_')[1]+'"' print 'Make sure the active object is a Mesh-type Object before trying to append Facepoints' #TODO: #- strict-er inputs (no errors allowed) #___________________________________________________________________________________________ #this function is used to give a bone weight to the current (existing) vert def SetWeight( BoneName=0, Weight=1.0, VertID='' ): #VertID is a TODO (should accept both list and int) global ActiveObject #verify we havn't switched objects to an invalid type: if ActiveObject != None: SD = VIEWER.Libs[3][ActiveObject][3] if VIEWER.Libs[3][ActiveObject][4] != '': ParentObject = VIEWER.Libs[3][VIEWER.Libs[3][ActiveObject][4]] if ParentObject[3][0] == "_Rig": #parent object must be a _Rig object if type(BoneName) == int: #check for the bone name in the parent _Rig oblect if BoneName < len(ParentObject[3][3]): #is the index w/in the bone count? BoneName = ParentObject[3][3][BoneName][0] #must be a string else: BoneName = 'Bone'+str(BoneName) #must be a string else: BoneName = 'Bone'+str(BoneName) else: BoneName = 'Bone'+str(BoneName) if SD[0]=="_Mesh": if len(SD[3][5]): #Has Primitives if len(SD[3][5][-1][1]): #Has facepoints if len(SD[3][0]): #Has Verts #WGrps,found,WGid = SD[3][4],0,0 WGrps,found = SD[3][4],0 Vid = SD[3][5][-1][1][-1][0] #vert index from current primitive's current facepoint if len(WGrps)>0: ''' while WGid < len(WGrps)-1 or not found: #faster (stops if found or at end) WGN,WGFs,WGVs = WGrps[WGid] if WGN == BoneName: #append Vid to an existing weight group WFid = len(WGFs) #assume the weight is a new weight try: WFid = WGFs.index(Weight) #try to get a valid weight index except: VIEWER.Libs[3][ActiveObject][3][3][4][WGid][1]+=[Weight] #append new weight VIEWER.Libs[3][ActiveObject][3][3][4][WGid][2]+=[[Vid,WFid]] found = 1 WGid += 1 ''' #^???throws an indexing error...??? for WGid,WG in enumerate(WGrps): WGN,WGFs,WGVs = WG if WGN == BoneName: #append Vid to an existing weight group WFid = len(WGFs) #assume the weight is a new weight try: WFid = WGFs.index(Weight) #try to get a valid weight index except: VIEWER.Libs[3][ActiveObject][3][3][4][WGid][1].append(Weight) #append new weight VIEWER.Libs[3][ActiveObject][3][3][4][WGid][2].append([Vid,WFid]) found = 1 #''' if not found: #append Vid to a new weight group VIEWER.Libs[3][ActiveObject][3][3][4]+=[[BoneName,[Weight],[[Vid,0]]]] #check get the vert index and append it to the specified weight #VIEWER.Libs[3][ActiveObject][3][3][-1][-1][4].append([Weight,Bones]) #TODO: #- use VID to index a specific vert. (some model formats may force you to use this) #(currently indexing the last used vert (OpenGL-style)) #___________________________________________________________________________________________ #defines a new material to be used def SetMaterial(Name="Material0"): global ActiveObject, ActiveMaterial #check if our material exists or create a new material MID = __GetMID(Name) if MID!='': #if so, update the material #Textures = VIEWER.Libs[4][MID][3] #preserve the textures ActiveMaterial = MID __LOG('---FORMAT---: set Active Material to: %s'%VIEWER.Libs[4][MID][0]) else: VIEWER.Libs[4] += [[Name, '', [[1.0,1.0,1.0,1.0],[1.0,1.0,1.0,1.0],[0.5,0.5,0.5,1.0],[0.0,0.0,0.0,0.0],25.0], [], [], []]] ActiveMaterial = len(VIEWER.Libs[4])-1 __LOG('---FORMAT---: created Material: %s'%Name) if VIEWER.Libs[3][ActiveObject][3][2] != ActiveMaterial: VIEWER.Libs[3][ActiveObject][3][2] = ActiveMaterial SetMaterial.func_defaults=( "Material"+str(len(VIEWER.Libs[4])), ) #set the colors of the current material def SetMatColors( Ambient = None, Diffuse = None, Specular = None, Emmisive = None, Shine = None ): global ActiveMaterial r = 1.0/255 if len(VIEWER.Libs[4])>0: try: AR,AG,AB,AA = Ambient if type(AR) == int: AR,AG,AB,AA = AR*r,AG*r,AB*r,AA*r except: AR,AG,AB,AA = VIEWER.Libs[4][ActiveMaterial][2][0] try: DR,DG,DB,DA = Diffuse if type(DR) == int: DR,DG,DB,DA = DR*r,DG*r,DB*r,DA*r except: DR,DG,DB,DA = VIEWER.Libs[4][ActiveMaterial][2][1] try: SR,SG,SB,SA = Specular if type(SR) == int: SR,SG,SB,SA = SR*r,SG*r,SB*r,SA*r except: SR,SG,SB,SA = VIEWER.Libs[4][ActiveMaterial][2][2] try: ER,EG,EB,EA = Emmisive if type(ER) == int: ER,EG,EB,EA = ER*r,EG*r,EB*r,EA*r except: ER,EG,EB,EA = VIEWER.Libs[4][ActiveMaterial][2][3] if Shine==None: Shine=VIEWER.Libs[4][ActiveMaterial][2][4] VIEWER.Libs[4][ActiveMaterial][2] = [[AR,AG,AB,AA],[DR,DG,DB,DA],[SR,SG,SB,SA],[ER,EG,EB,EA],Shine] __LOG('---FORMAT---: set Material colors to: %s'%str(VIEWER.Libs[4][ActiveMaterial][2])) #___________________________________________________________________________________________ def SetTexture(Name="Texture0"): global ActiveMaterial,ActiveTexture TID = __GetTID(Name) if TID!='': ActiveTexture = TID __LOG('---FORMAT---: set Active Texture to: %s'%VIEWER.Libs[6][TID][0]) else: VIEWER.Libs[6] += [[Name,[],[],[],'',[]]] #TexName,TexParams,EnvParams,TReserved2,ImageName,TReserved3 ActiveTexture = len(VIEWER.Libs[6])-1 __LOG('---FORMAT---: created Texture: %s'%Name) if ActiveMaterial!=None: if ActiveTexture not in VIEWER.Libs[4][ActiveMaterial][3]: VIEWER.Libs[4][ActiveMaterial][3] += [ActiveTexture] __LOG('---FORMAT---: added Texture to Material: %s'%VIEWER.Libs[4][ActiveMaterial][0]) SetTexture.func_defaults=( "Texture"+str(len(VIEWER.Libs[6])), ) #___________________________________________________________________________________________ def SetImage(Name="Image0",Width=0,Height=0,Data=[]): global ActiveTexture,ActiveImage resolved = 0 IID = __GetIID(Name) if IID!='': ActiveImage = IID __LOG('---FORMAT---: set Active Image to: %s'%VIEWER.Libs[7][IID][0]) else: #NOTE: Pallet not supported yet (last index) if type(Data) == list: VIEWER.Libs[7] += [[Name,Width,Height,Data,[]]] else: VIEWER.Libs[7] += [[Name,1,1,[[255,255,255,255]],[]]] ActiveImage = len(VIEWER.Libs[7])-1 __LOG('---FORMAT---: created Image: %s'%Name) if type(Data) == str: #image directory it = Data.split('.')[-1] #get the file type current,offset = COMMON.__c,COMMON.__o try: import sys __LOG('---FORMAT---: loading image data from %s'%Data) COMMON.ImportFile(Data,1) W,H,img,plt = sys.modules[COMMON._ImgScripts[it]].ImportImage(it) VIEWER.Libs[7][ActiveImage][1] = W VIEWER.Libs[7][ActiveImage][2] = H VIEWER.Libs[7][ActiveImage][3] = img VIEWER.Libs[7][ActiveImage][4] = plt del W; del H; del img; del plt #cleanup #resolved = 1 except: __LOG('---FORMAT---: encountered an error trying to read from the image.') import sys,traceback typ,val,tb=sys.exc_info()#;tb=traceback.extract_tb(i[2])[0] print traceback.print_exception( typ,val,tb#, #limit=2, #file=sys.stdout ) print COMMON.__c,COMMON.__o = current,offset if ActiveTexture!=None and not resolved: VIEWER.Libs[6][ActiveTexture][4] = Name __LOG('---FORMAT---: added Image to Texture: %s'%VIEWER.Libs[6][ActiveTexture][0]) SetImage.func_defaults=( "Image"+str(len(VIEWER.Libs[7])), ) #___________________________________________________________________________________________ #return the mesh-objects from either the specified scene, or from the object library def __Sort(List,Type): L=[] for ID,Object in enumerate(List): if type(Object)==int: if VIEWER.Libs[3][Object][3][0]==Type: L+=[Object] else: if Object[3][0]==Type: L+=[ID] return L def GetMeshObjects(Scene=''): if type(Scene)==str: if Scene=='': return __Sort(VIEWER.Libs[3], "_Mesh") else: return __Sort(VIEWER.Libs[2][VIEWER.Libs[2].index(Scene)][1], "_Mesh") elif type(Scene)==int: return Sort(VIEWER.Libs[2][Scene][1]) def GetRigObjects(Scene=''): if type(Scene)==str: if Scene=='': return __Sort(VIEWER.Libs[3], "_Rig") else: return __Sort(VIEWER.Libs[2][VIEWER.Libs[2].index(Scene)][1], "_Rig") elif type(Scene)==int: return Sort(VIEWER.Libs[2][Scene][1]) #TODO: better error handling on SceneLib.index(Scene) and SceneLib[Scene] #___________________________________________________________________________________________ def GetObjectName(Object=0): if type(Object)==int: return VIEWER.Libs[3][Object][0] elif type(Object)==str: return Object #___________________________________________________________________________________________ def GetVerts(Object=''): if type(Object)==int: return VIEWER.Libs[3][Object][3][3][0] elif type(Object)==str: VIEWER.Libs[3][__GetOID(Object)][3][3][0] #___________________________________________________________________________________________ def GetNormals(Object=''): if type(Object)==int: return VIEWER.Libs[3][Object][3][3][1] elif type(Object)==str: VIEWER.Libs[3][__GetOID(Object)][3][3][1] #___________________________________________________________________________________________ def GetColors(Object='',Channel=0): if type(Object)==int: return VIEWER.Libs[3][Object][3][3][2][Channel] elif type(Object)==str: VIEWER.Libs[3][__GetOID(Object)][3][3][2][Channel] #___________________________________________________________________________________________ def GetUVs(Object='',Channel=0): if type(Object)==int: return VIEWER.Libs[3][Object][3][3][3][Channel] elif type(Object)==str: VIEWER.Libs[3][__GetOID(Object)][3][3][3][Channel] #___________________________________________________________________________________________ def GetPrimitives(Object=''): if type(Object)==int: return VIEWER.Libs[3][Object][3][3][5] elif type(Object)==str: VIEWER.Libs[3][__GetOID(Object)][3][3][5] #___________________________________________________________________________________________ def AsTriangles( PrimitivesList, Option=0 ): Triangles,Quads = [],[] #NOTE: "Quads" is only for single primitive conversion for Primitive in PrimitivesList: index = 0;Tris = [3,[]] switch(Primitive[0]) if case(0): #points if option==(1 or 3): pass #primitive is not Tri/Quad else: Triangles+=[Primitive] if case(1): #lines if option==(1 or 3): pass #primitive is not Tri/Quad else: Triangles+=[Primitive] if case(2): #line-strips if option==(1 or 3): pass #primitive is not Tri/Quad else: Triangles+=[Primitive] if case(3): #line-loops if option==(1 or 3): pass #primitive is not Tri/Quad else: Triangles+=[Primitive] if case(4): #triangles if option==(1 or 3): Triangles+=Primitive[1] #single primitive else: Triangles+=[Primitive] if case(5): #tri-strips while index != len(Primitive[1])-2: T=[Primitive[1][index],Primitive[1][index+1],Primitive[1][index+2]] if T[0] != T[1] and T[0] != T[2] and T[1] != T[2]: Tris[1]+=(T.reverse() if index%2 else T) index += 1 if option==(1 or 3): Triangles+=Tris[1] #single primitive else: Triangles+=[Tris] if case(6): #tri-fans P=[Primitive[1][index]] while index != len(Primitive[1])-2: T=P+[Primitive[1][index+1],Primitive[1][index+2]] if T[0] != T[1] and T[0] != T[2] and T[1] != T[2]: Tris[1]+=(T.reverse() if index%2 else T) index += 1 if option==(1 or 3): Triangles+=Tris[1] #single primitive else: TrianglesList+=[Tris] if case(7): #quads while index != len(Primitive[1]): Q=[Primitive[1][index],Primitive[1][index+1],Primitive[1][index+2],Primitive[1][index+3]] Tris[1]+=[Q[0],Q[1],Q[2],Q[1],Q[2],Q[3]] #TODO: face flipping index += 4 switch(option) if case(0): Triangles+=[Tris] if case(1): Triangles+=Tris[1] if case(2): Triangles+=[Primitive] if case(3): Quads+=Primitive[1] if case(8): #quad-strips Qds=[] pass #unknown handling atm (TODO) if case(9): #Polygons pass #unknown handling atm (TODO) switch(Option) if case(0): return Triangles#................multiple triangle primitives if case(1): return [[3,Triangles]]#..........single triangle primitive if case(2): return Triangles#................multiple triangle and quad primitives if case(3): return [[3,Triangles],[6,Quads]]#single triangle and quad primitive ''' def convertFromTriangles( TrianglesList ): P=ConvertToTriangles(TrianglesList,1) #only works for single tris atm '''
{ "repo_name": "Universal-Model-Converter/UMC3.0a", "path": "data/FORMAT.py", "copies": "1", "size": "33654", "license": "mit", "hash": 6892526838806766000, "line_mean": 47.5627705628, "line_max": 143, "alpha_frac": 0.5560706008, "autogenerated": false, "ratio": 3.3124015748031495, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9181104203947263, "avg_score": 0.037473594331177196, "num_lines": 693 }
#1 #v 0.001 from ERROR import * """ TODO's: - SetLight(): ### I have to learn about these a little more :P """ #global public usage variables: global UGE_POINTS,UGE_LINES,UGE_LINESTRIP,UGE_LINELOOP,UGE_TRIANGLES,UGE_TRIANGLESTRIP,UGE_TRIANGLEFAN,UGE_QUADS,UGE_QUADSTRIP,UGE_POLYGON UGE_POINTS,UGE_LINES,UGE_LINESTRIP,UGE_LINELOOP,UGE_TRIANGLES,UGE_TRIANGLESTRIP,UGE_TRIANGLEFAN,UGE_QUADS,UGE_QUADSTRIP,UGE_POLYGON = [1<<s for s in range(10)] class __FormatHandler: class SceneManager: def __init__(self): self.RenameDefault=1 self.IDs={"Default_Scene":0} #indexing self.current="Default_Scene" _Scenes={"Default_Scene":[]} #{ SceneName : [ObjectIDs] } def NewName(self): return "Scene_%i"%(len(self.IDs)-self.RenameDefault) def HasScene(self,Name): #'return False' uses the currently active scene if type(Name)==str: #Scene Name if Name in self.IDs: #does the name exist? self.current=Name return True elif type(Name)==int: #Scene Index if -1<Name<len(self.IDs): #are we within range? self.current=self.IDs.keys()[self.IDs.values().index(Name)] #^not exactly the best method... (trying to avoid using another iterator) return True return False def AddScene(self,Name): if type(Name)==str: if self.RenameDefault: #is this the first scene? self._Scenes={Name:self._Scenes["Default_Scene"]} self.IDs={Name:0} self.current=Name self.RenameDefault=0 else: self._Scenes.update({Name:[]}) self.current=Name self.IDs.update({Name:len(self.IDs)}) else: pass #can't add scene with this name (or type) def CID(self): return self.IDs[self.current] #objecs always create a link to the current scene when created/called #(multiple scenes can reference the same object) def LinkObject(self,ID): #for objects only (so far) called from ObjectManager if ID not in self._Scenes[self.current]: self._Scenes[self.current]+=[ID] class ObjectManager: class _Rig: _Bones={} class _Object: LocX,LocY,LocZ=0.0,0.0,0.0 RotX,RotY,RotZ=0.0,0.0,0.0 ScaX,ScaY,ScaZ=1.0,1.0,1.0 ParentID='' #the data contained by the object: ('_Rig','_Mesh' ,'_Curve','_Surface','_NURBS','_DMesh') Data=[] DataName=None #this is set with the object name upon object creation DataType='' def __init__(self): self.IDs={} #for indexing objects self.current=None _Objects={} def NewName(self): return "Object_%i"%len(self.IDs) def HasObject(self,Name): #'return False' uses the currently active object if type(Name)==str: #Object Name if Name in self.IDs: #does the name exist? self.current=Name return True elif type(Name)==int: #Object Index if -1<Name<len(self.IDs): #are we within range? self.current=self.IDs.keys()[self.IDs.values().index(Name)] #^not exactly the best method... (trying to avoid using another iterator) return True return False def AddObject(self,Name): if type(Name)==str: self._Objects.update({Name:self._Object()}) self._Objects[Name].DataName=Name self.current=Name self.IDs.update({Name:len(self.IDs)}) #Scenes.LinkObject(self.IDs[self.current]) else: pass #can't add object with this name (or type) def CID(self): return self.IDs[self.current] def RenameObjectData(self,Name): self._Objects[self.current].DataName=Name def ParentObject(self,Name): pass def SetLocX(self,X): self._Objects[self.current].LocX=X def SetLocY(self,Y): self._Objects[self.current].LocY=Y def SetLocZ(self,Z): self._Objects[self.current].LocZ=Z def SetRotX(self,X): self._Objects[self.current].RotX=X def SetRotY(self,Y): self._Objects[self.current].RotY=Y def SetRotZ(self,Z): self._Objects[self.current].RotZ=Z def SetScaX(self,X): self._Objects[self.current].ScaX=X def SetScaY(self,Y): self._Objects[self.current].ScaY=Y def SetScaZ(self,Z): self._Objects[self.current].ScaZ=Z Scenes=SceneManager() Objects=ObjectManager() def Contents(self): print 'Scenes:',self.Scenes._Scenes print 'Objects:',self.Objects._Objects def GL_Draw(self): #Called by VIEWER to draw specific objects to the scene pass #def ToFormat(self): #returns SESv1 format #def FromFormat(self,fmt=[]): #sets data from SESv1 evaluated input data #def Clear(self): __Format=__FormatHandler() #------------------------------------------------------- # user functions: #------------------------------------------------------- #adds a new scene (renames the default scene), or activates an existing scene def ugeSetScene(Name=__Format.Scenes.NewName()): if not __Format.Scenes.HasScene(Name): __Format.Scenes.AddScene(Name) ugeSetScene.func_defaults=(__Format.Scenes.NewName(),) return __Format.Scenes.CID() #return the Current ID #adds a new object, or activates an existing object def ugeSetObject(Name=__Format.Objects.NewName()): if not __Format.Objects.HasObject(Name): __Format.Objects.AddObject(Name) CID = __Format.Objects.CID(); __Format.Scenes.LinkObject(CID) ugeSetObject.func_defaults=(__Format.Objects.NewName(),) return CID #return the Current ID def ugeSetObjectDataName(Name): __Format.Objects.RenameObjectData(Name) #set's the current object's parent def ugeSetObjectParent(Name): if __Format.Objects.HasObject(Name): __Format.Objects.ParentObject(Name) #resets the current object's Location def ugeSetObjectLoc(X=0.0,Y=0.0,Z=0.0): if (type(X)==list or type(X)==tuple) and len(X)==3: X,Y,Z=X elif type(X)==float: __Format.Objects.SetLocX(X);__Format.Objects.SetLocY(Y);__Format.Objects.SetLocZ(Z) #individual functions for those formats that need them <_< def ugeSetObjectLocX(X): __Format.Objects.SetLocX(X) def ugeSetObjectLocY(Y): __Format.Objects.SetLocY(Y) def ugeSetObjectLocZ(Z): __Format.Objects.SetLocZ(Z) #resets the current object's Rotation def ugeSetObjectRot(X=0.0,Y=0.0,Z=0.0): if (type(X)==list or type(X)==tuple) and len(X)==3: X,Y,Z=X elif type(X)==float: __Format.Objects.SetRotX(X);__Format.Objects.SetRotY(Y);__Format.Objects.SetRotZ(Z) def ugeSetObjectRotX(X): __Format.Objects.SetRotX(X) def ugeSetObjectRotY(Y): __Format.Objects.SetRotY(Y) def ugeSetObjectRotZ(Z): __Format.Objects.SetRotZ(Z) #resets the current object's Scale def ugeSetObjectSca(X=1.0,Y=1.0,Z=1.0): if (type(X)==list or type(X)==tuple) and len(X)==3: X,Y,Z=X elif type(X)==float: __Format.Objects.SetScaX(X);__Format.Objects.SetScaY(Y);__Format.Objects.SetScaZ(Z) def ugeSetObjectScaX(X): __Format.Objects.SetScaX(X) def ugeSetObjectScaY(Y): __Format.Objects.SetScaY(Y) def ugeSetObjectScaZ(Z): __Format.Objects.SetScaZ(Z) """ class old_format(): #global defaults (bypassing re-definition from functions (speedup)) DLRS=[0.0,0.0,0.0, 0.0,0.0,0.0, 1.0,1.0,1.0] DM=[[1.0,0.0,0.0,0.0], [0.0,1.0,0.0,0.0], [0.0,0.0,1.0,0.0], [0.0,0.0,0.0,1.0]] #___________________________________________________________________________________________ import VIEWER #VIEWER.Libs[MatNodes, Images, Textures, Materials, Scenes, Objects] #Active Data: ActiveScene = 0 ActiveObject = None ActiveMaterial = None ActivePrimitive = 0 #in active object def __GetOID(N): #check for specified object name/ID ID='' if type(N)==int: ID=('' if N>len(VIEWER.Libs[5]) else N) #N=1 else: #N="Object1" ###need a faster indexing method here ###VIEWER.Libs[5].index(N) won't work as VIEWER.Libs[5] values are lists with random internal datas for I,O in enumerate(VIEWER.Libs[5]): #TODO: use a while loop (stop the loop if found) if O[0]==N: ID=I return ID #return int() if found #___________________________________________________________________________________________ SceneCount = 0 #create a new scene, or activate the specified scene def SetScene( Name="Scene0" ): global SceneCount,ActiveScene if SceneCount==0: #change the default scene name VIEWER.Libs[4][0][0]=(Name if type(Name)==str else "Scene"+str(SceneCount)) SceneCount+=1 else: #user defined scenes already exist SceneIndex = None #TODO: usa a while loop for Index,Scene in enumerate(VIEWER.Libs[4]): #check for specified scene name/index if Scene[0]==Name or Index==Name: SceneIndex=Index if SceneIndex == None: #create a new scene VIEWER.Libs[4]+=[Name if type(Name)==str else "Scene"+str(SceneCount)] ActiveScene=len(VIEWER.Libs[4]) #set the active scene index to the newly added scene SceneCount+=1 else: ActiveScene=SceneIndex #set the active scene index to the specified scene SetScene.func_defaults=( "Scene"+str(SceneCount), ) #TODO: #- active scene rename: SetScene( [('Name' or Index), "NewName"] ) #^this will rename the scene while setting it to active #___________________________________________________________________________________________ ObjectSceneID = [] #the indexed object's scene index #create a new object in the active scene, or activate and change the data in a specified object #(if a specified object exists in another scene, that object's scene will be set as active) def SetObject( Name="Object0", Viewport=0, LocRotSca=[], Sub_Name='', ParentName='' ): global ActiveScene,ActiveObject,ObjectSceneID,DLRS ObjectLib=VIEWER.Libs[5] #Verify Data: (use Defaults if neccesary) N = (ObjectLib[Name][0] if (type(Name)==int and Name>-1 and Name<(len(ObjectLib)+1) #get the name of the specified object ) else (Name if type(Name)==str else "Object"+str(len(ObjectLib)))) #N must be a string VP = (Viewport if (Viewport>0 and Viewport<25) else 1) #must be 1 to 24 LRS= (DLRS if len(LocRotSca)!=9 else LocRotSca) #TODO: advanced LRS verification SD = ["",(N if (Sub_Name=='' or type(Sub_Name)!=str) else Sub_Name),[],[]] P = (__GetOID(ParentName) if ParentName!=('__REMOVE__' or '') else ParentName) OID=__GetOID(N) if len(VIEWER.Libs[5])>0 else '' #try to get an active object index if OID=='': #if this is a new object: VIEWER.Libs[5].append([N,VP,LRS,SD,(P if len(VIEWER.Libs[5])>0 else '')]) #ignore parent index if this is the first object VIEWER.Libs[4][ActiveScene][1]+=[len(VIEWER.Libs[5])-1] ObjectSceneID+=[ActiveScene] ActiveObject=len(VIEWER.Libs[5])-1 else: #set the active object to the specicified object and change it's data ActiveObject,ActiveScene = OID,ObjectSceneID[OID]; AO=ObjectLib[OID] VIEWER.Libs[5][OID]=[ AO[0], #reset the object's data: ((VP if Viewport!=0 else AO[1]) if AO[1]!=VP else AO[1]), ((LRS if LRS!=DLRS else AO[2]) if AO[2]!=LRS else AO[2]), [AO[3][0],(AO[3][1] if Sub_Name=='' else SD[1]),AO[3][2],AO[3][3]], #reset sub data name (not data) ((P if ObjectLib[OID][4]!=P else ObjectLib[OID][4]) if P!='__REMOVE__' else '')] SetObject.func_defaults=( "Object"+str(len(VIEWER.Libs[5])), 0, [], '', '' ) #TODO: #- verify the object doesn't have multiple parents (important) #- active object rename: SetObject( [('Name' or Index), "NewName"], ... ) #^this will rename the specified object while setting it active and editing it's data #___________________________________________________________________________________________ #set the active object's type to Rig and create a new bone within it, or change the data of an existing bone #(you will recieve an error if used on another Object type) #(you will also recieve an error if no object is defined) def SetBone( Name="Bone0", Viewport=0, LocRotSca=[], BindMtx=[], ParentName='', PreviousName='' ): global ActiveObject,BoneLib,N,VP,LRS,BM,PA,PR,DLRS BoneLib=VIEWER.Libs[5][ActiveObject][3][3] def GetID(S): #check for specified bone name/ID global BoneLib ID='' if type(S)==int: ID=('' if S>len(BoneLib) else S) #S=1 else: #S="Bone1" ###need a faster indexing method here ###BoneLib.index(N) won't work as BoneLib values are lists with random internal datas for I,B in enumerate(BoneLib): if B[0]==S: ID=I return ID #Verify Data: (use Defaults if neccesary) N = (Name if type(Name)==str else "Bone"+str(len(BoneLib))) VP = (Viewport if (Viewport>0 and Viewport<25) else 1) LRS= (DLRS if len(LocRotSca)!=9 else LocRotSca) #TODO: advanced LRS verification BM = (DM if len(BindMtx)!=4 else BindMtx) #TODO: advanced matrix verification PA = (GetID(ParentName) if ParentName!=('__REMOVE__' or '') else '') PR = (GetID(PreviousName) if PreviousName!='' else '') def Set(): global ActiveObject,N,VP,LRS,BM,PA,PR,BoneLib #manage the bone data: BID= GetID(N) if len(BoneLib)>0 else '' #try to get an active object index if BID=='': VIEWER.Libs[5][ActiveObject][3][3]+=[[N,VP,LRS,BM,PA,PR]] #add a new bone else: VIEWER.Libs[5][ActiveObject][3][3][BID]=[BoneLib[BID][0], #edit the specified bone ((VP if Viewport!=0 else BoneLib[BID][1]) if BoneLib[BID][1]!=VP else BoneLib[BID][1]), ((LRS if LRS!=DLRS else BoneLib[BID][2]) if BoneLib[BID][2]!=LRS else BoneLib[BID][2]), ((BM if BM!=DM44 else BoneLib[BID][3]) if BoneLib[BID][3]!=BM else BoneLib[BID][3]), ((PA if ParentName!='' else BoneLib[BID][4]) if BoneLib[BID][4]!=PA else BoneLib[BID][4]), ((PR if ParentName!='' else BoneLib[BID][5]) if BoneLib[BID][5]!=PR else BoneLib[BID][5])] #^- need to check for previous bone looping (in case of user error) #validate the active object if len(VIEWER.Libs[5])>0: if VIEWER.Libs[5][ActiveObject][3][0]=="": VIEWER.Libs[5][ActiveObject][3][0]="_Rig";Set() #set to "_Rig" and append a bone elif VIEWER.Libs[5][ActiveObject][3][0]=="_Rig": Set() #append a bone else: print 'Unable to append Bone to Object of type: "'+VIEWER.Libs[5][OID][3][0].split('_')[1]+'"\nignoring current data' else: print 'please define an object' SetBone.func_defaults=( "Bone"+str(len(VIEWER.Libs[5][ActiveObject][3][3])), 0, [], [], '', '' ) #TODO: #- instead of ignoring the invalid bone's data, create a new rig object to append it to #^you will then be able to parent the "ignored" bones to their proper object using a 3D editor #NOTE: only 1 object will be created to be the place-holder for the ignored bones (instead of 1 object for each ignored bone) #- rename bone: SetBone( [('Name' or Index), "NewName"], ... ) #^this will rename the specified bone while also editing it's data #___________________________________________________________________________________________ #set the active object's type to Mesh and append a primitive in it's data #(you will recieve an error if used on another Object type) #(you will also recieve an error if no object is defined) def SetPrimitive( Name=UMC_TRIANGLES ): #TODO: figure out how to get the var itself to display (not it's value) if len(VIEWER.Libs[5])>0: #validate the active object if VIEWER.Libs[5][ActiveObject][3][0]=="": VIEWER.Libs[5][ActiveObject][3][0]="_Mesh" VIEWER.Libs[5][ActiveObject][3][3]=[[],[],[[],[]],[[],[],[],[],[],[],[],[]],[],[]] VIEWER.Libs[5][ActiveObject][3][3][5]+=[[Name,[]]] #set to "_Mesh" and append a primitive elif VIEWER.Libs[5][ActiveObject][3][0]=="_Mesh": VIEWER.Libs[5][ActiveObject][3][3][5]+=[[Name,[]]] #append a primitive else: #return error print 'Unable to append Primitive to Object of type: "'+VIEWER.Libs[5][OID][3][0].split('_')[1]+'"\nignoring current data' else: print 'please define an object' SetPrimitive.func_defaults=( Name, ) #TODO: #- index the proper primitive to add facepoints to #^(I personally havn't seen a format you'd need this option for, but the possibility of it still lies about) #___________________________________________________________________________________________ #set the active object's type to Mesh and append a valid Vector List to it's data #(you will recieve an error if used on another Object type) #(you will also recieve an error if no object is defined) def SetVerts( List=[] ): global ActiveObject if len(VIEWER.Libs[5])>0: if VIEWER.Libs[5][ActiveObject][3][0]=="": VIEWER.Libs[5][ActiveObject][3][0]="_Mesh" VIEWER.Libs[5][ActiveObject][3][3]=[List,[],[[],[]],[[],[],[],[],[],[],[],[]],[],[]] elif VIEWER.Libs[5][ActiveObject][3][0]=="_Mesh": VIEWER.Libs[5][ActiveObject][3][3][0]=List else: print 'Unable to append Vert List to Object of type: "'+VIEWER.Libs[5][OID][3][0].split('_')[1]+'"\nignoring current data' else: print 'please define an object' def SetNormals( List=[] ): global ActiveObject if len(VIEWER.Libs[5])>0: if VIEWER.Libs[5][ActiveObject][3][0]=="": VIEWER.Libs[5][ActiveObject][3][0]="_Mesh" VIEWER.Libs[5][ActiveObject][3][3]=[[],List,[[],[]],[[],[],[],[],[],[],[],[]],[],[]] elif VIEWER.Libs[5][ActiveObject][3][0]=="_Mesh": VIEWER.Libs[5][ActiveObject][3][3][1]=List else: print 'Unable to append Normal List to Object of type: "'+VIEWER.Libs[5][OID][3][0].split('_')[1]+'"\nignoring current data' else: print 'please define an object' def SetColors( List0=[], List1=[] ): global ActiveObject if len(VIEWER.Libs[5])>0: if VIEWER.Libs[5][ActiveObject][3][0]=="": VIEWER.Libs[5][ActiveObject][3][0]="_Mesh" VIEWER.Libs[5][ActiveObject][3][3]=[[],[],[List0,List1],[[],[],[],[],[],[],[],[]],[],[]] elif VIEWER.Libs[5][ActiveObject][3][0]=="_Mesh": VIEWER.Libs[5][ActiveObject][3][3][2]=[List0,List1] else: print 'Unable to append Color Lists to Object of type: "'+VIEWER.Libs[5][OID][3][0].split('_')[1]+'"\nignoring current data' else: print 'please define an object' def SetUVs( List0=[], List1=[], List2=[], List3=[], List4=[], List5=[], List6=[], List7=[] ): global ActiveObject if len(VIEWER.Libs[5])>0: if VIEWER.Libs[5][ActiveObject][3][0]=="": VIEWER.Libs[5][ActiveObject][3][0]="_Mesh" VIEWER.Libs[5][ActiveObject][3][3]=[[],[],[[],[]],[List0,List1,List2,List3,List4,List5,List6,List7],[],[]] elif VIEWER.Libs[5][ActiveObject][3][0]=="_Mesh": VIEWER.Libs[5][ActiveObject][3][3][0]=[List0,List1,List2,List3,List4,List5,List6,List7] else: print 'Unable to append UV Lists to Object of type: "'+VIEWER.Libs[5][OID][3][0].split('_')[1]+'"\nignoring current data' else: print 'please define an object' #TODO: #- validate vector lists #- Validate replacements (don't replace a data with a default unless specified) #___________________________________________________________________________________________ #Vectors: [ X, Y(, Z) ] #Colors: [R,G,B,A] int( 0 : 255 ) OR float( 0.0 : 1.0 ) #^be careful not to specify an int when your type is float (for colors) #^2D Verts and Normals are allowd. #append a facepoint to the active primitive with the specified vectors #(colors and uv's in list format are assumed to be single channel, and are read as such) def SetFacepoint( Vert='', Normal='', Color='', UV='' ): global ActiveObject #verify we havn't switched objects to an invalid type before trying to add facepoints: if VIEWER.Libs[5][ActiveObject][3][0]=="_Mesh": #we can only set the facepoints of an active mesh object if len(VIEWER.Libs[5][ActiveObject][3][3])>0: #we can't append facepoints to an object with no primitives. Colors,UVs = VIEWER.Libs[5][ActiveObject][3][3][2],VIEWER.Libs[5][ActiveObject][3][3][3] def Index(value,List): #returns either a valid index or '' if type(value)==list: #[X,Y(,Z)] or [I/R(,A/G(,B(,A)))] try: return List.index(value) except: List+=[value]; return List.index(value) #vector or color elif type(value)==int: return value #index (doesn't validate against len(list)) elif type(value)==str: return '' #no vector (validate any string to '') CIDs = ( (Index(Color[0],Colors[0]) ,(Index(Color[1],Colors[1]) if len(Color)==2 else '') ) if type(Color)==tuple else (Index(Color,Colors[0]),'') ) UVIDs = ( (Index(UV[0],UVs[0]) ,(Index(UV[1],UVs[1]) if len(UV)>=2 else '') ,(Index(UV[2],UVs[2]) if len(UV)>=3 else '') ,(Index(UV[3],UVs[3]) if len(UV)>=4 else '') ,(Index(UV[4],UVs[4]) if len(UV)>=5 else '') ,(Index(UV[5],UVs[5]) if len(UV)>=6 else '') ,(Index(UV[6],UVs[6]) if len(UV)>=7 else '') ,(Index(UV[7],UVs[7]) if len(UV)==8 else '') ) if type(UV)==tuple else (Index(UV,UVs[0]),'','','','','','','') ) VIEWER.Libs[5][ActiveObject][3][3][5][-1][1]+=[ [Index(Vert,VIEWER.Libs[5][ActiveObject][3][3][0]),Index(Normal,VIEWER.Libs[5][ActiveObject][3][3][1]),CIDs,UVIDs] ] else: print 'unable to append to a non-existant primitive' else: print 'Unable to append Facepoint to Object of type: "'+VIEWER.Libs[5][OID][3][0].split('_')[1]+'"' print 'Make sure the active object is a Mesh-type Object before trying to append Facepoints' #TODO: #- strict-er inputs (no errors allowed) #___________________________________________________________________________________________ #this function is used to give a bone weight to the current (existing) vert def SetWeight( BoneName=0, Weight=1.0, VertID='' ): #VertID is a TODO (should accept both list and int) global ActiveObject #verify we havn't switched objects to an invalid type: if ActiveObject != None: SD = VIEWER.Libs[5][ActiveObject][3] if VIEWER.Libs[5][ActiveObject][4] != '': ParentObject = VIEWER.Libs[5][VIEWER.Libs[5][ActiveObject][4]] if ParentObject[3][0] == "_Rig": #parent object must be a _Rig object if type(BoneName) == int: #check for the bone name in the parent _Rig oblect if BoneName < len(ParentObject[3][3]): #is the index w/in the bone count? BoneName = ParentObject[3][3][BoneName][0] #must be a string else: BoneName = 'Bone'+str(BoneName) #must be a string else: BoneName = 'Bone'+str(BoneName) else: BoneName = 'Bone'+str(BoneName) if SD[0]=="_Mesh": if len(SD[3][5]): #Has Primitives if len(SD[3][5][-1][1]): #Has facepoints if len(SD[3][0]): #Has Verts #WGrps,found,WGid = SD[3][4],0,0 WGrps,found = SD[3][4],0 Vid = SD[3][5][-1][1][-1][0] #vert index from current primitive's current facepoint if len(WGrps)>0: ''' while WGid < len(WGrps)-1 or not found: #faster (stops if found or at end) WGN,WGFs,WGVs = WGrps[WGid] if WGN == BoneName: #append Vid to an existing weight group WFid = len(WGFs) #assume the weight is a new weight try: WFid = WGFs.index(Weight) #try to get a valid weight index except: VIEWER.Libs[5][ActiveObject][3][3][4][WGid][1]+=[Weight] #append new weight VIEWER.Libs[5][ActiveObject][3][3][4][WGid][2]+=[[Vid,WFid]] found = 1 WGid += 1 ''' #^???throws an indexing error...??? for WGid,WG in enumerate(WGrps): WGN,WGFs,WGVs = WG if WGN == BoneName: #append Vid to an existing weight group WFid = len(WGFs) #assume the weight is a new weight try: WFid = WGFs.index(Weight) #try to get a valid weight index except: VIEWER.Libs[5][ActiveObject][3][3][4][WGid][1].append(Weight) #append new weight VIEWER.Libs[5][ActiveObject][3][3][4][WGid][2].append([Vid,WFid]) found = 1 #''' if not found: #append Vid to a new weight group VIEWER.Libs[5][ActiveObject][3][3][4]+=[[BoneName,[Weight],[[Vid,0]]]] #check get the vert index and append it to the specified weight #VIEWER.Libs[5][ActiveObject][3][3][-1][-1][4].append([Weight,Bones]) #TODO: #- use VID to index a specific vert. (some model formats may force you to use this) #(currently indexing the last used vert (OpenGL-style)) #___________________________________________________________________________________________ #return the mesh-objects from either the specified scene, or from the object library def GetMeshObjects(Scene=''): def Sort(List): L=[] for ID,Object in enumerate(List): if type(Object)==int: if VIEWER.Libs[5][Object][3][0]=="_Mesh": L+=[Object] else: if Object[3][0]=="_Mesh": L+=[ID] return L if type(Scene)==str: if Scene=='': return Sort(VIEWER.Libs[5]) else: return Sort(VIEWER.Libs[4][VIEWER.Libs[4].index(Scene)][1]) elif type(Scene)==int: return Sort(VIEWER.Libs[4][Scene][1]) #TODO: better error handling on SceneLib.index(Scene) and SceneLib[Scene] #___________________________________________________________________________________________ def GetObjectName(Object=0): if type(Object)==int: return VIEWER.Libs[5][Object][0] #___________________________________________________________________________________________ def GetVerts(Object=''): if type(Object)==int: return VIEWER.Libs[5][Object][3][3][0] elif type(Object)==str: VIEWER.Libs[5][__GetOID(Object)][3][3][0] #___________________________________________________________________________________________ def GetNormals(Object=''): if type(Object)==int: return VIEWER.Libs[5][Object][3][3][1] elif type(Object)==str: VIEWER.Libs[5][__GetOID(Object)][3][3][1] #___________________________________________________________________________________________ def GetColors(Object='',Channel=0): if type(Object)==int: return VIEWER.Libs[5][Object][3][3][2][Channel] elif type(Object)==str: VIEWER.Libs[5][__GetOID(Object)][3][3][2][Channel] #___________________________________________________________________________________________ def GetUVs(Object='',Channel=0): if type(Object)==int: return VIEWER.Libs[5][Object][3][3][3][Channel] elif type(Object)==str: VIEWER.Libs[5][__GetOID(Object)][3][3][3][Channel] #___________________________________________________________________________________________ def GetPrimitives(Object=''): if type(Object)==int: return VIEWER.Libs[5][Object][3][3][5] elif type(Object)==str: VIEWER.Libs[5][__GetOID(Object)][3][3][5] #___________________________________________________________________________________________ def AsTriangles( PrimitivesList, Option=0 ): global UMC_POINTS,UMC_LINES,UMC_LINESTRIP,UMC_LINELOOP,UMC_TRIANGLES,UMC_TRIANGLESTRIP,UMC_TRIANGLEFAN,UMC_QUADS,UMC_QUADSTRIP,UMC_POLYGON Triangles,Quads = [],[] #NOTE: "Quads" is only for single primitive conversion for PID,PFPs in PrimitivesList: index = 0;Tris = [3,[]] if PID==UMC_POINTS: if Option==(1 or 3): pass #primitive is not Tri/Quad else: Triangles+=[[PID,PFPs]] if PID==UMC_LINES: if Option==(1 or 3): pass #primitive is not Tri/Quad else: Triangles+=[[PID,PFPs]] if PID==UMC_LINESTRIP: if Option==(1 or 3): pass #primitive is not Tri/Quad else: Triangles+=[[PID,PFPs]] if PID==UMC_LINELOOP: if Option==(1 or 3): pass #primitive is not Tri/Quad else: Triangles+=[[PID,PFPs]] if PID==UMC_TRIANGLES: if Option==(1 or 3): Triangles+=PFPs #single primitive else: Triangles+=[[PID,PFPs]] if PID==UMC_TRIANGLESTRIP: while index != len(PFPs)-2: T=PFPs[index:index+3] if T[0] != T[1] and T[0] != T[2] and T[1] != T[2]: Tris[1]+=(list(reversed(T)) if index%2 else T) index += 1 if Option==(1 or 3): Triangles+=Tris[1] #single primitive else: Triangles+=[Tris] if PID==UMC_TRIANGLEFAN: P=[PFPs[index]] while index != len(PFPs)-2: T=P+[PFPs[index+1],PFPs[index+2]] if T[0] != T[1] and T[0] != T[2] and T[1] != T[2]: Tris[1]+=(list(reversed(T)) if index%2 else T) index += 1 if Option==(1 or 3): Triangles+=Tris[1] #single primitive else: TrianglesList+=[Tris] if PID==UMC_QUADS: while index != len(PFPs): Q=[PFPs[index],PFPs[index+1],PFPs[index+2],PFPs[index+3]] Tris[1]+=[Q[0],Q[1],Q[2],Q[1],Q[2],Q[3]] #TODO: face flipping index += 4 if Option==0: Triangles+=[Tris] if Option==1: Triangles+=Tris[1] if Option==2: Triangles+=[[PID,PFPs]] if Option==3: Quads+=PFPs if PID==UMC_QUADSTRIP: #quad-strips Qds=[] pass #unknown handling atm (TODO) if PID==UMC_POLYGON: #Polygons pass #unknown handling atm (TODO) if Option==0: return Triangles#................multiple triangle primitives if Option==1: return [[3,Triangles]]#..........single triangle primitive if Option==2: return Triangles#................multiple triangle and quad primitives if Option==3: return [[3,Triangles],[6,Quads]]#single triangle and quad primitive ''' def convertFromTriangles( TrianglesList ): P=ConvertToTriangles(TrianglesList,1) #only works for single tris atm ''' """
{ "repo_name": "Universal-Model-Converter/UMC3.0a", "path": "dev tests and files/data (scrapped dev5 attempt)/FORMAT.py", "copies": "1", "size": "32810", "license": "mit", "hash": 4522680218362861000, "line_mean": 50.4263322884, "line_max": 159, "alpha_frac": 0.5353245962, "autogenerated": false, "ratio": 3.535179398771684, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9490460000764543, "avg_score": 0.016008798841428164, "num_lines": 638 }
#1 #v 0.001 #I don't have a TOC here yet as everything constantly changes import COMMON #file vars and functions for import/export processing import VIEWER #mainly for the toggles from VIEWER import __GL,__GLU #GL functions from VIEWER import __pyg ''' from COMMON import Scripts #Shapes (private) #Widgets (private) def Button(Text,X,Y,W,H,): pass def Browser(): import os Dir='C:/'; done=0 clicked = 0 while not done: items = os.listdir(Dir) cancel = Button('Cancel') if not cancel: if Button('..'): Dir else: #need a better RT method >_> #TODO: parse the list and collect info first for item in items: if Button(item): #draw Clicked button clicked=1 else: #draw unclicked button if clicked: #action clicked=0 if os.path.isdir(Dir+item): Dir+=(item+'/') else: done=1 return Dir+item else: pass else: done=1 return None ''' #the GL selection/feedback buffers are a bit complicated for me, #so I've defined my own method derived from GL. (should be slightly faster than re-defining everything) #this method compaires the hitdefs with the current selection and changes the state of a valid hit W_States = {} #this stores the mouse state for the current widget #further state processing can be done by the widget itself. # { name: [L,M,R,O] } #O - mouseOver W_Info = {} #this stores the state info of each widget #this determines weather a toggle is active, or a selection has yet to be made __UpdateHits=True #allow for hit updates W_HitDefs = {} #this stores the hit-area for each widget #this is constantly cleared and updated during state changes # { name: [X1,Y1,X2,Y2] } pw,ph = 1.0/800,1.0/600 #----------------------------------- #I/O process functions def __ImportModel(): pass def __ExportModel(): pass def __ImportAnim(): pass def __ExportAnim(): pass def __Browser(Scripts): #overlays GUI when activated (Clears hit-defs to avoid improper activation) #return file_path, Module pass #----------------------------------- #widget resources FontSize=0 def __font(x,y,size,text,color=(0,0,0,255)): global pw,ph,FontSize #__GL.glEnable(__GL.GL_TEXTURE_2D) #Create Font #to increase performance, only create a new font when changing the size if size != FontSize: F=__pyg.font.Font('fonts/tahoma.ttf',size) #don't use .fon files w,h=F.size(text) #_w,_h=1,1 #GL-modified width/height (binary multiple) #while _w<w: _w<<=1 #while _h<h: _h<<=1 #fsurf=__pyg.Surface((w,h),__pyg.SRCALPHA) #fsurf.blit(__pyg.transform.flip(F.render(text,True,color), False, True),(0,0)) #Create GL-Font Image #w,h=fsurf.get_size() image=__pyg.transform.flip(F.render(text,True,color), False, True).get_buffer().raw #get raw pixel data # Create Texture __GL.glGenTextures(1) '''__GL.glBindTexture(__GL.GL_TEXTURE_2D, 0) # 2d texture (x and y size) __GL.glPixelStorei(__GL.GL_UNPACK_ALIGNMENT,1) __GL.glTexImage2D(__GL.GL_TEXTURE_2D, 0, 3, _w, _h, 0, __GL.GL_BGRA, __GL.GL_UNSIGNED_BYTE, image) __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_T, __GL.GL_CLAMP) __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_REPEAT) __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_T, __GL.GL_REPEAT) __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_MAG_FILTER, __GL.GL_NEAREST) __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_MIN_FILTER, __GL.GL_NEAREST) __GL.glTexEnvf(__GL.GL_TEXTURE_ENV, __GL.GL_TEXTURE_ENV_MODE, __GL.GL_DECAL) w*=pw; h*=ph __GL.glBegin(__GL.GL_QUADS) __GL.glColor4f(0.0,0.0,0.0,color[3]*(1.0/255)) __GL.glVertex2f(x,y); __GL.glTexCoord2f(0.0,0.0) __GL.glVertex2f(x+w,y); __GL.glTexCoord2f(1.0,0.0) __GL.glVertex2f(x+w,y+h); __GL.glTexCoord2f(1.0,1.0) __GL.glVertex2f(x,y+h); __GL.glTexCoord2f(0.0,1.0) __GL.glEnd()''' __GL.glRasterPos2f(float(x)*pw if type(x)==int else x , float(y+h)*ph if type(y)==int else y+(h*ph) ) __GL.glDrawPixels(w,h,__GL.GL_BGRA,__GL.GL_UNSIGNED_BYTE,image) del(image) #remove the old buffer #__GL.glDisable(__GL.GL_TEXTURE_2D) #----------------------------------- #internal widgets (bound to change) def __DropBox(X,Y,W,Na,Items,Def=0,Text=''): global W_States,W_Info,W_HitDefs,__UpdateHits global pw,ph X2,Y2 = X+(pw*(W*10)),Y+(ph*20) #Widget init info try: W_States[Na] except KeyError: W_States.update({Na:[0,0,0,False]}) W_Info.update({Na:[Def,False]}) if __UpdateHits: W_HitDefs.update({Na:[X,Y,X2+(pw*15),Y2]}) #Widget logic L,M,R,O = W_States[Na] if L==2: W_Info[Na][1]=True W_States[Na][0]=0 State = W_Info[Na] __GL.glBegin(__GL.GL_QUADS) __GL.glColor4f(1.0,1.0,1.0,0.25) __GL.glVertex2f(X,Y) __GL.glVertex2f(X2,Y) __GL.glVertex2f(X2,Y2) __GL.glVertex2f(X,Y2) __GL.glColor4f(0.0,0.0,0.0,0.1) __GL.glVertex2f(X2,Y) __GL.glVertex2f(X2+(pw*15),Y) __GL.glVertex2f(X2+(pw*15),Y2) __GL.glVertex2f(X2,Y2) __GL.glEnd() __font(X+(5*pw),Y+(2*ph),12,Na,(0,0,0,100)) if State[1]: W_HitDefs={} __UpdateHits=False #prevent hit updates from other widgets #once we've made our selection, we can then allow hit updates remove=False for i,v in enumerate(Items): #we have to create custom widget defs for each entry here N = '%s_%s_Sel%i'%(Na,v,i) #Na+v+'_Sel'+str(i) x1,y1,x2,y2=X,Y+((Y2-Y)*(i+1)),X2,Y2+((Y2-Y)*(i+1)) try: W_States[N] except KeyError: W_States.update({N:[0,0,0,False]}) #mouse updates W_HitDefs.update({N:[x1,y1,x2,y2]}) #these should be the only hits avaliable l,m,r,o = W_States[N] #all we need to worry about here, is the state, and the hit-def if o: __GL.glColor4f(0.375,0.375,0.375,0.75) else: __GL.glColor4f(0.0,0.0,0.0,0.5) __GL.glBegin(__GL.GL_QUADS) __GL.glVertex2f(x1,y1) __GL.glVertex2f(x2,y1) __GL.glVertex2f(x2,y2) __GL.glVertex2f(x1,y2) __GL.glEnd() __font(x1+(5*pw),y1+(2*ph),12,v,(200,200,200,100)) if l==2: W_Info[Na]=[i,False] #State should not be an index remove=True if remove: for i,v in enumerate(Items): #clear the buffers of these widgets n = '%s_%s_Sel%i'%(Na,v,i) W_States.pop(n) W_HitDefs.pop(n) __UpdateHits=True return State[0] def __TButton(X,Y,Na,St=False,Text=''): global W_States,W_Info,W_HitDefs,__UpdateHits global pw,ph #Widget init info try: W_States[Na] except KeyError: W_States.update({Na:[0,0,0,False]}) W_Info.update({Na:St}) if __UpdateHits: W_HitDefs.update({Na:[X,Y,X+(pw*20),Y+(ph*20)]}) #Widget logic L,M,R,O = W_States[Na] if L==2: W_Info[Na]=(False if W_Info[Na] else True) W_States[Na][0]=0 State = W_Info[Na] if State: __GL.glColor4f(0.0,0.0,0.0,0.25) else: __GL.glColor4f(0.0,0.0,0.0,0.1) __GL.glBegin(__GL.GL_QUADS) __GL.glVertex2f(X,Y) __GL.glVertex2f(X+(pw*20),Y) __GL.glVertex2f(X+(pw*20),Y+(ph*20)) __GL.glVertex2f(X,Y+(ph*20)) __GL.glEnd() __font(X+(25*pw),Y+(2*ph),12,Text,(0,0,0,100)) return State def __Button(X1,Y1,X2,Y2,Na,Text=''): global pw,ph def __BrowseBar(X1,Y1,W): global pw,ph #----------------------------------- #panel drawing functions def __ModelPanel(): global pw,ph __BrowseBar(pw*10,ph*40,180) def __AnimPanel(): global pw,ph pass def __DisplayPanel(X1,X2): global pw,ph VIEWER.TOGGLE_LIGHTING = __TButton(pw*(X1+11),ph*31,'EnLight',True,'Lighting') VIEWER.TOGGLE_WIREFRAME = __TButton(pw*(X1+11),ph*56,'EnWire',False,'Wireframe') VIEWER.TOGGLE_BONES = __DropBox(pw*(X1+11),ph*81,10,'Draw Bones',['None','Standard','Overlay (X-Ray)'],0) #reversed drawing order here so fonts overlay properly if VIEWER.TOGGLE_3D==2: VIEWER.TOGGLE_3D_MODE[1] = [1./60,1./120][__DropBox(pw*(X1+251),ph*81,5,'Freq (WIP)',['60hz','120hz'],0)] if VIEWER.TOGGLE_3D==1: VIEWER.TOGGLE_3D_MODE[0] = __DropBox(pw*(X1+251),ph*81,5,'Colors',['R|GB','G|RB','B|RG'],0) VIEWER.TOGGLE_3D = __DropBox(pw*(X1+131),ph*81,10,'3D Drawing',['Off','Analglyph','Shutter'],0) VIEWER.TOGGLE_ORTHO = __DropBox(pw*(X1+131),ph*56,10,'Projection',['Perspective','Orthographic'],1) VIEWER.TOGGLE_GRID = [2 if VIEWER.TOGGLE_GRID>2 else VIEWER.TOGGLE_GRID,3,4][ __DropBox(pw*(X1+131),ph*31,10,'Display',['Grid','Floor','Off'],0)] #''' def __ControlPanel(X1,X2): global pw,ph pass #----------------------------------- def __ExPanel(X1,Y1,X2,Y2,EB,Na,MX=0,MY=0,St=True): #returns current state for other panels global W_States,W_Info,W_HitDefs,__UpdateHits global pw,ph #Widget init info try: W_States[Na] except KeyError: W_States.update({Na:[0,0,0,False]}) W_Info.update({Na:St}) #Widget logic L,M,R,O = W_States[Na] if L==2: W_Info[Na]=(False if W_Info[Na] else True) W_States[Na][0]=0 State = W_Info[Na] if State: __GL.glBegin(__GL.GL_QUADS) __GL.glColor4f(0.5,0.5,0.5,0.8) #model (left) panel __GL.glVertex2f(X1,Y1) __GL.glVertex2f(X1,Y2) __GL.glVertex2f(X2,Y2) __GL.glVertex2f(X2,Y1) __GL.glEnd() #60x15px rectangle if EB==0: #top EBX1,EBY1,EBX2,EBY2=(X1+((X2-X1)/2)-(pw*30)),Y1,(X1+((X2-X1)/2)+(pw*30)),Y1+(ph*15) TPX1,TPY1 = EBX1+(pw*25),EBY1+(ph*5) TPX2,TPY2 = EBX1+(pw*30),EBY1+(ph*10) TPX3,TPY3 = EBX1+(pw*35),EBY1+(ph*5) elif EB==1: #right EBX1,EBY1,EBX2,EBY2=X2-(pw*15),((Y2-Y1)/2)-(ph*30),X2,((Y2-Y1)/2)+(ph*30) TPX1,TPY1 = EBX1+(pw*10),EBY1+(ph*25) TPX2,TPY2 = EBX1+(pw*5),EBY1+(ph*30) TPX3,TPY3 = EBX1+(pw*10),EBY1+(ph*35) elif EB==2: #bottom EBX1,EBY1,EBX2,EBY2=(X1+((X2-X1)/2)-(pw*30)),Y2-(ph*15),(X1+((X2-X1)/2)+(pw*30)),Y2 TPX1,TPY1 = EBX1+(pw*25),EBY1+(ph*10) TPX2,TPY2 = EBX1+(pw*30),EBY1+(ph*5) TPX3,TPY3 = EBX1+(pw*35),EBY1+(ph*10) elif EB==3: #left EBX1,EBY1,EBX2,EBY2=X1,((Y2-Y1)/2)-(ph*30),X1+(pw*15),((Y2-Y1)/2)+(ph*30) TPX1,TPY1 = EBX1+(pw*5),EBY1+(ph*25) TPX2,TPY2 = EBX1+(pw*10),EBY1+(ph*30) TPX3,TPY3 = EBX1+(pw*5),EBY1+(ph*35) #is the panel expanded? if not State: if EB==0: #top Eq=((Y2-Y1)-(ph*15)) EBY1,EBY2=EBY1+Eq,EBY2+Eq TPY1,TPY2,TPY3=TPY1+(Eq+(ph*5)),TPY2+(Eq-(ph*5)),TPY3+(Eq+(ph*5)) elif EB==1: #right Eq=((X2-X1)-(pw*15)) EBX1,EBX2=EBX1-Eq,EBX2-Eq TPX1,TPX2,TPX3=TPX1-(Eq+(pw*5)),TPX2-(Eq-(pw*5)),TPX3-(Eq+(pw*5)) elif EB==2: #bottom Eq=((Y2-Y1)-(ph*15)) EBY1,EBY2=EBY1-Eq,EBY2-Eq TPY1,TPY2,TPY3=TPY1-(Eq+(ph*5)),TPY2-(Eq-(ph*5)),TPY3-(Eq+(ph*5)) elif EB==3: #left Eq=((X2-X1)-(pw*15)) EBX1,EBX2=EBX1+Eq,EBX2+Eq TPX1,TPX2,TPX3=TPX1+(Eq+(pw*5)),TPX2+(Eq-(pw*5)),TPX3+(Eq+(pw*5)) __GL.glColor4f(0.5,0.5,0.5,0.8) __GL.glBegin(__GL.GL_QUADS) #(just the BG color behind the toggle button) __GL.glVertex2f(EBX1+MX,EBY1+MY) __GL.glVertex2f(EBX1+MX,EBY2+MY) __GL.glVertex2f(EBX2+MX,EBY2+MY) __GL.glVertex2f(EBX2+MX,EBY1+MY) __GL.glEnd() if __UpdateHits: W_HitDefs.update({Na:[EBX1+MX,EBY1+MY,EBX2+MX,EBY2+MY]}) __GL.glColor4f(0.0,0.0,0.0,0.2) __GL.glBegin(__GL.GL_QUADS) __GL.glVertex2f(EBX1+MX,EBY1+MY) __GL.glVertex2f(EBX1+MX,EBY2+MY) __GL.glVertex2f(EBX2+MX,EBY2+MY) __GL.glVertex2f(EBX2+MX,EBY1+MY) __GL.glEnd() __GL.glBegin(__GL.GL_TRIANGLES) __GL.glVertex2f(TPX1+MX,TPY1+MY) __GL.glVertex2f(TPX2+MX,TPY2+MY) __GL.glVertex2f(TPX3+MX,TPY3+MY) __GL.glEnd() return State def __DrawGUI(w,h,RotMatrix): #called directly by the display function after drawing the scene global pw,ph #the GUI is drawn over the scene by clearing the depth buffer pw,ph=1./w,1./h global W_HitDefs W_HitDefs = {} #clear the hitdefs to avoid improper activation __GL.glMatrixMode(__GL.GL_PROJECTION) __GL.glLoadIdentity() #glOrtho(-2*P, 2*P, -2, 2, -100, 100) __GLU.gluOrtho2D(0.0, 1.0, 1.0, 0.0) #TODO update the viewport with the pixel range instead of 1.0 (less GUI calculations will be needed) __GL.glMatrixMode(__GL.GL_MODELVIEW) __GL.glClear( __GL.GL_DEPTH_BUFFER_BIT ) __GL.glPolygonMode(__GL.GL_FRONT_AND_BACK,__GL.GL_FILL) __GL.glLoadIdentity() __GL.glEnable(__GL.GL_BLEND) __GL.glDisable(__GL.GL_DEPTH_TEST) __GL.glDisable(__GL.GL_TEXTURE_2D) __GL.glDisable(__GL.GL_LIGHTING) __GL.glBegin(__GL.GL_QUADS) __GL.glColor4f(0.4,0.4,0.4,0.8) #options toggle __GL.glVertex2f(pw*0,ph*0) __GL.glVertex2f(pw*w,ph*0) __GL.glVertex2f(pw*w,ph*20) __GL.glVertex2f(pw*0,ph*20) __GL.glEnd() __GL.glColor4f(0.0,0.0,0.0,0.2) __GL.glBegin(__GL.GL_TRIANGLES) __GL.glVertex2f(pw*((w/2)-10),ph*6) __GL.glVertex2f(pw*((w/2)+10),ph*6) __GL.glVertex2f(pw*(w/2),ph*15) __GL.glEnd() M = __ExPanel(pw*0,ph*21,pw*210,ph*h,1,'MODEL') if M: __ModelPanel() A = __ExPanel(pw*(w-210),ph*21,pw*w,ph*h,3,'ANIM') if A: __AnimPanel() D = __ExPanel(pw*(211 if M else 1),ph*21,pw*(w-(211 if A else 1)),ph*150,2,'DSPL',(0 if M else pw*105)+(0 if A else pw*-105)) if D: __DisplayPanel(210 if M else 0,-210 if A else 0) C = __ExPanel(pw*(211 if M else 1),ph*(h-150),pw*(w-(211 if A else 1)),ph*h,0,'CTRL',(0 if M else pw*105)+(0 if A else pw*-105)) if C: __ControlPanel(210 if M else 0,-210 if A else 0) #__font(40,40,14,"testing",(128,0,0,100)) __GL.glDisable(__GL.GL_BLEND) __GL.glEnable(__GL.GL_DEPTH_TEST) #axis __GL.glLineWidth(1.0) __GL.glPushMatrix() __GL.glTranslatef(pw*(228 if M else 17),ph*(h-(167 if C else 17)),0) __GL.glScalef(pw*600,ph*600,1) __GL.glMultMatrixf(RotMatrix) __GL.glColor3f(1.0,0.0,0.0) __GL.glBegin(__GL.GL_LINES); __GL.glVertex3f(0.0,0.0,0.0); __GL.glVertex3f(0.02,0.0,0.0); __GL.glEnd() #X __GL.glTranslatef(0.0145,0.0,0.0); __GL.glRotatef(90, 0.0, 1.0, 0.0) #__GLUT.glutSolidCone(0.003, 0.011, 8, 1) __GL.glRotatef(-90, 0.0, 1.0, 0.0); __GL.glTranslatef(-0.0145,0.0,0.0) __GL.glColor3f(0.0,1.0,0.0) __GL.glBegin(__GL.GL_LINES); __GL.glVertex3f(0.0,0.0,0.0); __GL.glVertex3f(0.0,-0.02,0.0); __GL.glEnd() #Y __GL.glTranslatef(0.0,-0.0145,0.0); __GL.glRotatef(90, 1.0, 0.0, 0.0) #__GLUT.glutSolidCone(0.003, 0.011, 8, 1) __GL.glRotatef(-90, 1.0, 0.0, 0.0); __GL.glTranslatef(0.0,0.0145,0.0) __GL.glColor3f(0.0,0.0,1.0) __GL.glBegin(__GL.GL_LINES); __GL.glVertex3f(0.0,0.0,0.0); __GL.glVertex3f(0.0,0.0,0.02); __GL.glEnd() #Z __GL.glTranslatef(0.0,0.0,0.0145) #__GLUT.glutSolidCone(0.003, 0.011, 8, 1) __GL.glTranslatef(0.0,0.0,-0.0145) __GL.glColor3f(0.5,0.5,0.5) ; #__GLUT.glutSolidSphere(0.003, 8, 4) __GL.glPopMatrix() lastHit = [0,False] #last hit record to be compaired with current hit record [ button, state ] def __CheckHit(b,x,y,s): #checks if the hit (click) executes a command L,M,R,U,D=range(1,6) for name in W_HitDefs: #we currently want to concentrait on if we have a hit (o is not handled here) X1,Y1,X2,Y2 = W_HitDefs[name] #Hit Area l,m,r,o = W_States[name] #we only want the release states to last 1 frame if X1<x<X2 and Y1<y<Y2: #are we in the hit area of this widget? #if we have our hit, then we can updte the name state of our hit if b==L: if s: W_States[name][0]=1 #we have clicked else: W_States[name][0]=2 #we have released if b==M: if s: W_States[name][1]=1 #we have clicked else: W_States[name][1]=2 #we have released if b==R: if s: W_States[name][2]=1 #we have clicked else: W_States[name][2]=2 #we have released else: #do we have any states to clean up? #this would happen if we click a widget, then move out of it's area if l==1: W_States[name][0]=0 if m==1: W_States[name][1]=0 if r==1: W_States[name][2]=0 #release states are to be taken care of by the widget. def __CheckPos(x,y): #checks the new mouse position when moved import sys for name in W_HitDefs: #we want to concentrait on if we're over a hit area X1,Y1,X2,Y2 = W_HitDefs[name] #Hit Area #are we in the hit area of this widget? if X1<x<X2 and Y1<y<Y2: W_States[name][3]=True else: W_States[name][3]=False def __initGUI(): __pyg.font.init()
{ "repo_name": "Universal-Model-Converter/UMC3.0a", "path": "dev tests and files/data (scrapped dev5 attempt)/GUI_update.py", "copies": "1", "size": "17612", "license": "mit", "hash": -5439508331457262000, "line_mean": 32.7413793103, "line_max": 142, "alpha_frac": 0.5642743584, "autogenerated": false, "ratio": 2.5113360901183515, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3575610448518351, "avg_score": null, "num_lines": null }
#1 #v 0.001 import COMMON #file vars and functions for import/export processing import VIEWER #mainly for the toggles from VIEWER import __GL,__GLU#,__GLUT #GL functions ''' from COMMON import Scripts #Shapes (private) #Widgets (private) def Button(Text,X,Y,W,H,): pass def Browser(): import os Dir='C:/'; done=0 clicked = 0 while not done: items = os.listdir(Dir) cancel = Button('Cancel') if not cancel: if Button('..'): Dir else: #need a better RT method >_> #TODO: parse the list and collect info first for item in items: if Button(item): #draw Clicked button clicked=1 else: #draw unclicked button if clicked: #action clicked=0 if os.path.isdir(Dir+item): Dir+=(item+'/') else: done=1 return Dir+item else: pass else: done=1 return None ''' #the GL selection/feedback buffers are a bit complicated for me, #so I'm defining my own method derived from GL. (should be faster) #GL wanted me to redraw everything during the selection and then after the selection... #my method compaires the hitdefs with the current selection and changes the state of a valid hit W_HitDefs = {} #this stores the hit-area for each widget (constantly updated during state changes) W_States = {} #this stores the state of each widget W_Types = {} #this stores the type of each widget (proper hit-logic handling depends on type) pw,ph = 800,600 def __ImportModel(fpath, filterID): #Model import process pass def __ExportModel(fpath, filterID): #Model export process pass def __ImportAnim(fpath, filterID): #Anim import process pass def __ExportAnim(fpath, filterID): #Anim export process pass def __TButton(X,Y,Na,St=False,Text=''): global pw,ph try: State = W_States[Na] except KeyError: State = St W_States.update({Na:St}) W_Types.update({Na:'toggle'}) W_HitDefs.update({Na:[X,Y,X+(pw*20),Y+(ph*20)]}) if State: __GL.glColor4f(0.0,0.0,0.0,0.25) else: __GL.glColor4f(0.0,0.0,0.0,0.1) __GL.glBegin(__GL.GL_QUADS) __GL.glVertex2f(X,Y) __GL.glVertex2f(X+(pw*20),Y) __GL.glVertex2f(X+(pw*20),Y+(ph*20)) __GL.glVertex2f(X,Y+(ph*20)) __GL.glEnd() return State def __Button(X1,Y1,X2,Y2,Na,Text=''): global pw,ph pass def __Browser(): #overlays GUI when activated (Clears hit-defs to avoid improper activation) #return file_path, filter_index pass def __BrowseBar(X1,Y1,W): global pw,ph pass def __ExPanel(X1,Y1,X2,Y2,EB,Na,MX=0,MY=0,St=True): #returns current state for other widgets global pw,ph try: State = W_States[Na] except KeyError: State = St W_States.update({Na:St}) W_Types.update({Na:'toggle'}) if State: __GL.glBegin(__GL.GL_QUADS) __GL.glColor4f(0.5,0.5,0.5,0.8) #model (left) panel __GL.glVertex2f(X1,Y1) __GL.glVertex2f(X1,Y2) __GL.glVertex2f(X2,Y2) __GL.glVertex2f(X2,Y1) __GL.glEnd() #60x15px rectangle if EB==0: #top EBX1,EBY1,EBX2,EBY2=(X1+((X2-X1)/2)-(pw*30)),Y1,(X1+((X2-X1)/2)+(pw*30)),Y1+(ph*15) TPX1,TPY1 = EBX1+(pw*25),EBY1+(ph*5) TPX2,TPY2 = EBX1+(pw*30),EBY1+(ph*10) TPX3,TPY3 = EBX1+(pw*35),EBY1+(ph*5) elif EB==1: #right EBX1,EBY1,EBX2,EBY2=X2-(pw*15),((Y2-Y1)/2)-(ph*30),X2,((Y2-Y1)/2)+(ph*30) TPX1,TPY1 = EBX1+(pw*10),EBY1+(ph*25) TPX2,TPY2 = EBX1+(pw*5),EBY1+(ph*30) TPX3,TPY3 = EBX1+(pw*10),EBY1+(ph*35) elif EB==2: #bottom EBX1,EBY1,EBX2,EBY2=(X1+((X2-X1)/2)-(pw*30)),Y2-(ph*15),(X1+((X2-X1)/2)+(pw*30)),Y2 TPX1,TPY1 = EBX1+(pw*25),EBY1+(ph*10) TPX2,TPY2 = EBX1+(pw*30),EBY1+(ph*5) TPX3,TPY3 = EBX1+(pw*35),EBY1+(ph*10) elif EB==3: #left EBX1,EBY1,EBX2,EBY2=X1,((Y2-Y1)/2)-(ph*30),X1+(pw*15),((Y2-Y1)/2)+(ph*30) TPX1,TPY1 = EBX1+(pw*5),EBY1+(ph*25) TPX2,TPY2 = EBX1+(pw*10),EBY1+(ph*30) TPX3,TPY3 = EBX1+(pw*5),EBY1+(ph*35) #is the panel expanded? if not State: if EB==0: #top Eq=((Y2-Y1)-(ph*15)) EBY1,EBY2=EBY1+Eq,EBY2+Eq TPY1,TPY2,TPY3=TPY1+(Eq+(ph*5)),TPY2+(Eq-(ph*5)),TPY3+(Eq+(ph*5)) elif EB==1: #right Eq=((X2-X1)-(pw*15)) EBX1,EBX2=EBX1-Eq,EBX2-Eq TPX1,TPX2,TPX3=TPX1-(Eq+(pw*5)),TPX2-(Eq-(pw*5)),TPX3-(Eq+(pw*5)) elif EB==2: #bottom Eq=((Y2-Y1)-(ph*15)) EBY1,EBY2=EBY1-Eq,EBY2-Eq TPY1,TPY2,TPY3=TPY1-(Eq+(ph*5)),TPY2-(Eq-(ph*5)),TPY3-(Eq+(ph*5)) elif EB==3: #left Eq=((X2-X1)-(pw*15)) EBX1,EBX2=EBX1+Eq,EBX2+Eq TPX1,TPX2,TPX3=TPX1+(Eq+(pw*5)),TPX2+(Eq-(pw*5)),TPX3+(Eq+(pw*5)) __GL.glColor4f(0.5,0.5,0.5,0.8) __GL.glBegin(__GL.GL_QUADS) #(just the BG color behind the toggle button) __GL.glVertex2f(EBX1+MX,EBY1+MY) __GL.glVertex2f(EBX1+MX,EBY2+MY) __GL.glVertex2f(EBX2+MX,EBY2+MY) __GL.glVertex2f(EBX2+MX,EBY1+MY) __GL.glEnd() W_HitDefs.update({Na:[EBX1+MX,EBY1+MY,EBX2+MX,EBY2+MY]}) __GL.glColor4f(0.0,0.0,0.0,0.2) __GL.glBegin(__GL.GL_QUADS) __GL.glVertex2f(EBX1+MX,EBY1+MY) __GL.glVertex2f(EBX1+MX,EBY2+MY) __GL.glVertex2f(EBX2+MX,EBY2+MY) __GL.glVertex2f(EBX2+MX,EBY1+MY) __GL.glEnd() __GL.glBegin(__GL.GL_TRIANGLES) __GL.glVertex2f(TPX1+MX,TPY1+MY) __GL.glVertex2f(TPX2+MX,TPY2+MY) __GL.glVertex2f(TPX3+MX,TPY3+MY) __GL.glEnd() return State ORTHO = True def __DrawGUI(w,h,RotMatrix): #called directly by the display function after drawing the scene global pw,ph #the GUI is drawn over the scene by clearing the depth buffer pw,ph=1./w,1./h global W_HitDefs W_HitDefs = {} #clear the hitdefs to avoid improper activation __GL.glMatrixMode(__GL.GL_PROJECTION) __GL.glLoadIdentity() #glOrtho(-2*P, 2*P, -2, 2, -100, 100) __GLU.gluOrtho2D(0.0, 1.0, 1.0, 0.0) __GL.glMatrixMode(__GL.GL_MODELVIEW) __GL.glClear( __GL.GL_DEPTH_BUFFER_BIT ) __GL.glPolygonMode(__GL.GL_FRONT_AND_BACK,__GL.GL_FILL) __GL.glLoadIdentity() __GL.glEnable(__GL.GL_BLEND) __GL.glDisable(__GL.GL_DEPTH_TEST) __GL.glDisable(__GL.GL_LIGHTING) __GL.glBegin(__GL.GL_QUADS) __GL.glColor4f(0.4,0.4,0.4,0.8) #options toggle __GL.glVertex2f(pw*0,ph*0) __GL.glVertex2f(pw*w,ph*0) __GL.glVertex2f(pw*w,ph*20) __GL.glVertex2f(pw*0,ph*20) __GL.glEnd() __GL.glColor4f(0.0,0.0,0.0,0.2) __GL.glBegin(__GL.GL_TRIANGLES) __GL.glVertex2f(pw*((w/2)-10),ph*6) __GL.glVertex2f(pw*((w/2)+10),ph*6) __GL.glVertex2f(pw*(w/2),ph*15) __GL.glEnd() M = __ExPanel(pw*0,ph*21,pw*210,ph*h,1,'MODEL') if M: __BrowseBar(pw*10,ph*40,180) A = __ExPanel(pw*(w-210),ph*21,pw*w,ph*h,3,'ANIM') D = __ExPanel(pw*(211 if M else 1),ph*21,pw*(w-(211 if A else 1)),ph*150,2,'DSPL',(0 if M else pw*105)+(0 if A else pw*-105)) if D: VIEWER.TOGGLE_LIGHTING = __TButton(pw*(221 if M else 11),ph*31,'EnLight',True,'Lighting') VIEWER.TOGGLE_WIREFRAME = __TButton(pw*(221 if M else 11),ph*56,'EnWire',False,'Wireframe') VIEWER.TOGGLE_BONES = __TButton(pw*(221 if M else 11),ph*81,'EnBone',True,'Bones') global ORTHO if VIEWER.TOGGLE_ORTHO != ORTHO: W_States['EnOrtho'] = VIEWER.TOGGLE_ORTHO; ORTHO = VIEWER.TOGGLE_ORTHO #HACK ORTHO = __TButton(pw*(321 if M else 111),ph*31,'EnOrtho',True,'Ortho') VIEWER.TOGGLE_ORTHO = ORTHO VIEWER.TOGGLE_3D = __TButton(pw*(321 if M else 111),ph*56,'En3D',False,'3D Analglyph') VIEWER.TOGGLE_NORMALS = __TButton(pw*(321 if M else 111),ph*81,'EnNrm',False,'Normals') C = __ExPanel(pw*(211 if M else 1),ph*(h-150),pw*(w-(211 if A else 1)),ph*h,0,'CTRL',(0 if M else pw*105)+(0 if A else pw*-105)) __GL.glDisable(__GL.GL_BLEND) __GL.glEnable(__GL.GL_DEPTH_TEST) #axis __GL.glLineWidth(1.0) __GL.glPushMatrix() __GL.glTranslatef(pw*(228 if M else 17),ph*(h-(167 if C else 17)),0) __GL.glScalef(pw*600,ph*600,1) __GL.glMultMatrixf(RotMatrix) __GL.glColor3f(1.0,0.0,0.0) __GL.glBegin(__GL.GL_LINES); __GL.glVertex3f(0.0,0.0,0.0); __GL.glVertex3f(0.02,0.0,0.0); __GL.glEnd() #X __GL.glTranslatef(0.0145,0.0,0.0); __GL.glRotatef(90, 0.0, 1.0, 0.0) #__GLUT.glutSolidCone(0.003, 0.011, 8, 1) __GL.glRotatef(-90, 0.0, 1.0, 0.0); __GL.glTranslatef(-0.0145,0.0,0.0) __GL.glColor3f(0.0,1.0,0.0) __GL.glBegin(__GL.GL_LINES); __GL.glVertex3f(0.0,0.0,0.0); __GL.glVertex3f(0.0,-0.02,0.0); __GL.glEnd() #Y __GL.glTranslatef(0.0,-0.0145,0.0); __GL.glRotatef(90, 1.0, 0.0, 0.0) #__GLUT.glutSolidCone(0.003, 0.011, 8, 1) __GL.glRotatef(-90, 1.0, 0.0, 0.0); __GL.glTranslatef(0.0,0.0145,0.0) __GL.glColor3f(0.0,0.0,1.0) __GL.glBegin(__GL.GL_LINES); __GL.glVertex3f(0.0,0.0,0.0); __GL.glVertex3f(0.0,0.0,0.02); __GL.glEnd() #Z __GL.glTranslatef(0.0,0.0,0.0145) #__GLUT.glutSolidCone(0.003, 0.011, 8, 1) __GL.glTranslatef(0.0,0.0,-0.0145) __GL.glColor3f(0.5,0.5,0.5) ; #__GLUT.glutSolidSphere(0.003, 8, 4) __GL.glPopMatrix() def __ResizeGUI(w,h): pass def __Click(b,x,y): pass def __Release(b,x,y): pass def __Motion(b,x,y,rx,ry): pass def __KeyPress(k): pass def __KeyRelease(k): pass def __initGUI(): pass lastHit = [0,False] #last hit record to be compaired with current hit record [ button, state ] def __CheckHit(b,x,y,s): #checks if the hit (click) executes a command #b - mouse-button (0,1,2 = L,M,R) #x,y hit position #s - state 1 - 0 = execute (full click) # state starts at 0 # 1 means we've clicked a button (we can change our area during this) # 0 means we've released #the state will cause the area to have different affects on different widgets when a particular button is pressed. #print ['L','M','R'][b]+' - '+str([x,y])+' - '+str(s) #print str(x)+','+str(y) #print HitDefs for name in W_HitDefs: X1,Y1,X2,Y2 = W_HitDefs[name] #Hit Area if X1<x<X2 and Y1<y<Y2: #are we in the hit area of this widget? if W_Types[name]=='toggle': if not s: #make sure we update upon click-release W_States[name]=(False if W_States[name] else True) elif W_Types[name]=='button': if s: #Click W_States[name][0]=True if not s: #Release W_States[name][1]=True #leave the false-state changes up to the functions def __CheckPos(x,y): #checks the new mouse position when moved pass
{ "repo_name": "Universal-Model-Converter/UMC3.0a", "path": "dev tests and files/data backups/GUI_dev45_port.py", "copies": "1", "size": "10228", "license": "mit", "hash": 3866764479750810000, "line_mean": 30.3742331288, "line_max": 129, "alpha_frac": 0.6143918655, "autogenerated": false, "ratio": 2.2071644367716874, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.33215563022716876, "avg_score": null, "num_lines": null }
#1 #v 0.001 import COMMON #file vars and functions for import/export processing import VIEWER #mainly for the toggles from VIEWER import __GL,__GLU,__pyg from array import array as __arr class __Widget: class _event: def __init__(self): self.gainFocus=False #True for the first frame the cursor enters the hitspace self.loseFocus=False #True for the first frame the cursor leaves the hitspace self.hasFocus=False #True if the cursor is in the hitspace self.clickL=False #True if the L mouse button was clicked self.clickM=False #True if the M mouse button was clicked self.clickR=False #True if the R mouse button was clicked self.holdL=False #True if the L mouse button is held self.holdM=False #True if the M mouse button is held self.holdR=False #True if the R mouse button is held self.releaseL=False #True if the L mouse button was released self.releaseM=False #True if the M mouse button was released self.releaseR=False #True if the R mouse button was released self.scrollU=False #True if scrolling up self.scrollD=False #True if scrolling down self.allowKeys=False #triggered by a widget self.keyPress=False #True if a key was pressed self.keyHold=False #True if a key is being held self.keyRelease=False#True if a key was released def __init__(self): self.info=None self.motionX=0 self.motionY=0 self.key=None self.event=self._event() class __Layer: from data.VIEWER import __GL,__pyg class __PrimitiveCollector: from data.VIEWER import __GL class __Primitive: def __init__(self,primitive,color,v1,v2,v3,v4=None): self.color=color self.primitive=primitive self.v1=v1; self.v2=v2; self.v3=v3; self.v4=v4 def __init__(self): self.primitives={} def AddTri(self,v1,v2,v3,color=(0,0,0,0)): self.primitives[len(self.primitives)]=__Primitive(__GL.GL_TRIANGLES,color,v1,v2,v3) def AddQuad(self,v1,v2,v3,v4,color=(0,0,0,0)): self.primitives[len(self.primitives)]=__Primitive(__GL.GL_QUADS,color,v1,v2,v3,v4) class __FontCollector: class __String: def __init__(self,text,size,color,x,y,X,Y): self.color=color self.text=text; self.size=size self.x=x; self.y=y self.X=X; self.Y=Y def __init__(self): self.strings={} def AddString(self,text,size,x,y,X=None,Y=None,color=(0,0,0,255)): self.strings[len(self.strings)]=__String(text,size,color,x,y,X,Y) def __init__(self): self.stack={} #draws FG before BG with FG over BG (alphas are not mixed) self.overlay={} #clears the depth buffer and disables depth testing before drawing (alphas are mixed) self.font={} #same as Overly def AddStack(self): self.stack[0]=self.__PrimitiveCollector() def AddOverlay(self): self.overlay[len(self.overlay)]=self.__PrimitiveCollector() self.font[len(self.font)]=self.__FontCollector() def draw(self): __GL.glEnable(__GL.GL_DEPTH_TEST) for sid in self.stack: #should return order as 0+ (0 being the FG, [-1] the BG) d=(len(stack)-sid)*.01 primitives=self.stack[sid].primitives #faster access (I think) for pid in primitives: p=primitives[pid] __GL.glBegin(p.primitive) __GL.glColor4iv(p.color) __GL.glVertex3fv(p.v1+[d]) __GL.glVertex3fv(p.v2+[d]) __GL.glVertex3fv(p.v3+[d]) if p.v4!=None: __GL.glVertex3fv(p.v4+[d]) __GL.glEnd() __GL.glDisable(__GL.GL_DEPTH_TEST) FontSize=0 for oid in self.overlay: primitives=self.overlay[oid].primitives for pid in primitives: p=primitives[pid] __GL.glBegin(p.primitive) __GL.glColor4iv(p.color) __GL.glVertex2fv(p.v1) __GL.glVertex2fv(p.v2) __GL.glVertex2fv(p.v3) if p.v4!=None: __GL.glVertex2fv(p.v4) __GL.glEnd() strings=self.font[oid].strings for sid in strings: tet,size=strings[sid].text,strings[sid].size if size!= FontSize: F=__pyg.font.Font('fonts/tahoma.ttf',size) #don't use .fon files FontSize=size w,h=F.size(text) image=__pyg.transform.flip(F.render(text,True,strings[sid].color), False, True).get_buffer().raw #get raw pixel data x,y,X,Y = strings[sid].x,strings[sid].y,strings[sid].X,strings[sid].Y px=x*pw if type(x)==int else x py=y*ph if type(y)==int else y #center to the area: (if specified) if x2!=None: px+=((X if type(X)==float else float(X)*pw)-px)/2; px-=(w*pw)/2 if y2!=None: py+=((Y if type(Y)==float else float(Y)*ph)-py)/2; py-=(h*ph)/2 py+=(h*ph) __GL.glRasterPos2f(px,py) __GL.glDrawPixels(w,h,__GL.GL_BGRA,__GL.GL_UNSIGNED_BYTE,image) del(image) #remove the old buffer layer={} #GUI layering info (collection buffers) layer[0]=__layer() #updated once, modified, and reused #Drawing Order: #layer[0] # stack[0] #FG (not influenced by BG) # primitive[0] #these primitives are drawn first with a depth of ((len(stack)-stack_index)*.01) # primitive[1] # primitive[2] # stack[1] #BG # primitive[0] # primitive[1] # # overlay[0] #a layer drawn over the stack-layer # primitive[0] # primitive[1] # font[0] #the font that goes over this overlay-layer # text[0] # text[1] # text[2] # # overlay[1] #overlays previous font overlay and stack # primitive[0] # primitive[1] # font[1] # text[0] # #layer[1] #(used for browsers, errors, and other popups) # stack[0] #overlays layer[0] # primitive[0] # stack[1] # primitive[0] # # overlay[0] # primitive[0] # font[0] # text[0] # # overlay[1] # primitive[0] # font[1] # text[0] #this contains the info for each widget Widgets = {} #{ 'name':__widget() } HitDefs = {} #{ 'name':[0.0,0.0,0.0,0.0] } #stores the hit rectangle #the event handler manages the widgets by their hit-defs. #if the mouse does something within the widget area, the widget is updated AllowHitUpdates=True global __AllowVIEWERControl;__AllowVIEWERControl=True #----------------------------------- #I/O process functions def __ImportModelBrowser(): pass def __ExportModelBrowser(): pass def __ImportAnimBrowser(): pass def __ExportAnimBrowser(): pass #----------------------------------- #widget resources """ FontSize=0 def __font(x,y,size,text,color=(0,0,0,255),x2=None,y2=None): global pw,ph,FontSize #__GL.glEnable(__GL.GL_TEXTURE_2D) #Create Font #to increase performance, only create a new font when changing the size if size != FontSize: F=__pyg.font.Font('fonts/tahoma.ttf',size) #don't use .fon files w,h=F.size(text) #lsz = F.get_linesize() #_w,_h=1,1 #GL-modified width/height (binary multiple) #while _w<w: _w<<=1 #while _h<h: _h<<=1 #fsurf=__pyg.Surface((w,h),__pyg.SRCALPHA) #fsurf.blit(__pyg.transform.flip(F.render(text,True,color), False, True),(0,0)) #Create GL-Font Image #w,h=fsurf.get_size() image=__pyg.transform.flip(F.render(text,True,color), False, True).get_buffer().raw #get raw pixel data # Create Texture __GL.glGenTextures(1) '''__GL.glBindTexture(__GL.GL_TEXTURE_2D, 0) # 2d texture (x and y size) __GL.glPixelStorei(__GL.GL_UNPACK_ALIGNMENT,1) __GL.glTexImage2D(__GL.GL_TEXTURE_2D, 0, 3, _w, _h, 0, __GL.GL_BGRA, __GL.GL_UNSIGNED_BYTE, image) __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_T, __GL.GL_CLAMP) __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_REPEAT) __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_T, __GL.GL_REPEAT) __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_MAG_FILTER, __GL.GL_NEAREST) __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_MIN_FILTER, __GL.GL_NEAREST) __GL.glTexEnvf(__GL.GL_TEXTURE_ENV, __GL.GL_TEXTURE_ENV_MODE, __GL.GL_DECAL) w*=pw; h*=ph __GL.glBegin(__GL.GL_QUADS) __GL.glColor4f(0.0,0.0,0.0,color[3]*(1.0/255)) __GL.glVertex2f(x,y); __GL.glTexCoord2f(0.0,0.0) __GL.glVertex2f(x+w,y); __GL.glTexCoord2f(1.0,0.0) __GL.glVertex2f(x+w,y+h); __GL.glTexCoord2f(1.0,1.0) __GL.glVertex2f(x,y+h); __GL.glTexCoord2f(0.0,1.0) __GL.glEnd()''' px=x*pw if type(x)==int else x py=y*ph if type(y)==int else y #center to the area: (if specified) if x2!=None: px+=((x2 if type(x2)==float else float(x2)*pw)-px)/2; px-=(w*pw)/2 if y2!=None: py+=((y2 if type(y2)==float else float(y2)*ph)-py)/2; py-=(h*ph)/2 py+=(h*ph) __GL.glRasterPos2f(px,py) __GL.glDrawPixels(w,h,__GL.GL_BGRA,__GL.GL_UNSIGNED_BYTE,image) del(image) #remove the old buffer #__GL.glDisable(__GL.GL_TEXTURE_2D) return (w,h) """ #----------------------------------- #internal widgets (bound to change) def __DropBox(X,Y,W,Na,Items,Def=0,Text=''): global Widgets,HitDefs,pw,ph global AllowHitUpdates #convert pixel values to screen ranges X2,Y2 = X+(pw*W),Y+(ph*20) #EG: XPosition = (1.0/ScreenWidth)*XPixelPos #positioning precalculations pw15 = pw*15 pw5 = pw*5 ph2 = ph*2 sy = Y2-Y #Widget init info if Na not in Widgets.keys(): Widgets[Na]=__Widget() Widgets[Na].info=[Def,False] #[selectionID,isOpen] if AllowHitUpdates: HitDefs.update({Na:[X,Y,X2+pw15,Y2]}) #Widget logic if Widgets[Na].event.releaseL: Widgets[Na].info[1]=True #isOpen = True State = Widgets[Na].info __GL.glBegin(__GL.GL_QUADS) __GL.glColor4f(1.0,1.0,1.0,0.25) __GL.glVertex2f(X,Y) __GL.glVertex2f(X2,Y) __GL.glVertex2f(X2,Y2) __GL.glVertex2f(X,Y2) __GL.glColor4f(0.0,0.0,0.0,0.1) __GL.glVertex2f(X2,Y) __GL.glVertex2f(X2+pw15,Y) __GL.glVertex2f(X2+pw15,Y2) __GL.glVertex2f(X2,Y2) __GL.glEnd() __font(X+pw5,Y+ph2,12,Na,(0,0,0,100)) if State[1]: #the box has been clicked HitDefs.clear() AllowHitUpdates=False #prevent hit updates from other widgets #(once we've made our selection, we can then allow hit updates) remove=False for i,v in enumerate(Items): #generate a custom widget name using the main name, the item's text, and the enumerant value N = '%s_%s_Sel%i'%(Na,v,i) x1,y1,x2,y2=X,Y+(sy*(i+1)),X2,Y2+(sy*(i+1)) #we have to create a new widget for each entry here if N not in Widgets.keys(): Widgets[N]=__Widget() #test the loop run (doesn't re-create widgets) HitDefs.update({N:[x1,y1,x2,y2]}) if Widgets[N].event.hasFocus: __GL.glColor4f(0.375,0.375,0.375,0.75) elif Widgets[N].event.holdL: __GL.glColor4f(0.5,0.5,0.5,0.75) else: __GL.glColor4f(0.0,0.0,0.0,0.5) __GL.glBegin(__GL.GL_QUADS) __GL.glVertex2f(x1,y1) __GL.glVertex2f(x2,y1) __GL.glVertex2f(x2,y2) __GL.glVertex2f(x1,y2) __GL.glEnd() __font(x1+pw5,y1+ph2,12,v,(200,200,200,100)) #apply the selection and set to remove these widgets when LMB is released if Widgets[N].event.releaseL: Widgets[Na].info=[i,False]; remove=True #add a few widgets to define the click-off area #(anywhere on the screen that's not in this widget's range) # ^clicking will close the widget and keep it at it's current selection _DAN=['%s_DeActivator%i'%(Na,i) for i in range(4)] #custom deactivator names if _DAN[0] not in Widgets.keys(): Widgets[_DAN[0]]=__Widget() Widgets[_DAN[1]]=__Widget() Widgets[_DAN[2]]=__Widget() Widgets[_DAN[3]]=__Widget() HitDefs.update({_DAN[0]:[0.0,0.0,X,1.0]}) #left HitDefs.update({_DAN[1]:[X2,0.0,1.0,1.0]}) #right HitDefs.update({_DAN[2]:[X,0.0,X2,Y2]}) #top (Y2 because the main widget has no control here) HitDefs.update({_DAN[3]:[X,y2,X2,1.0]}) #bottom #the logic to test for and execute a click-off if any([Widgets[_DAN[0]].event.clickL,Widgets[_DAN[0]].event.clickM,Widgets[_DAN[0]].event.clickR, Widgets[_DAN[1]].event.clickL,Widgets[_DAN[1]].event.clickM,Widgets[_DAN[1]].event.clickR, Widgets[_DAN[2]].event.clickL,Widgets[_DAN[2]].event.clickM,Widgets[_DAN[2]].event.clickR, Widgets[_DAN[3]].event.clickL,Widgets[_DAN[3]].event.clickM,Widgets[_DAN[3]].event.clickR]): Widgets[Na].info[1]=False #isOpen = False remove=True if remove: #remove the selection widgets and click-off widgets for i,v in enumerate(Items): Widgets.pop('%s_%s_Sel%i'%(Na,v,i)); Widgets.pop(_DAN[0]) #left Widgets.pop(_DAN[1]) #right Widgets.pop(_DAN[2]) #top (Y2 because the widget has no control here) Widgets.pop(_DAN[3]) #bottom HitDefs.clear() AllowHitUpdates=True return State[0] def __TButton(X,Y,Na,St=False,Text=''): global Widgets,HitDefs,pw,ph global AllowHitUpdates #positioning precalculations pw20 = pw*20 ph20 = ph*20 #Widget init info if Na not in Widgets.keys(): Widgets[Na]=__Widget() Widgets[Na].info=St #toggle state if AllowHitUpdates: HitDefs.update({Na:[X,Y,X+pw20,Y+ph20]}) #Widget logic if Widgets[Na].event.releaseL: Widgets[Na].info=(False if Widgets[Na].info else True) State = Widgets[Na].info if State: __GL.glColor4f(0.0,0.0,0.0,0.25) else: __GL.glColor4f(0.0,0.0,0.0,0.1) __GL.glBegin(__GL.GL_QUADS) __GL.glVertex2f(X,Y) __GL.glVertex2f(X+pw20,Y) __GL.glVertex2f(X+pw20,Y+ph20) __GL.glVertex2f(X,Y+ph20) __GL.glEnd() __font(X+(pw*25),Y+(ph*2),12,Text,(0,0,0,100)) return State def __Button(X1,Y1,X2,Y2,Na,Text='',fontcolor=(0,0,0,255),St=False): global Widgets,HitDefs,pw,ph global AllowHitUpdates #Widget init info if Na not in Widgets.keys(): Widgets[Na]=__Widget(); Widgets[Na].info=['button',St] if AllowHitUpdates: HitDefs.update({Na:[X1,Y1,X2,Y2]}) #Widget logic if Widgets[Na].event.releaseL: Widgets[Na].info[1]=True if Widgets[Na].event.clickL or Widgets[Na].event.holdL: __GL.glColor4f(0.0,0.0,0.0,0.1) else: __GL.glColor4f(0.0,0.0,0.0,0.175) __GL.glBegin(__GL.GL_QUADS) __GL.glVertex2f(X1,Y1) __GL.glVertex2f(X2,Y1) __GL.glVertex2f(X2,Y2) __GL.glVertex2f(X1,Y2) __GL.glEnd() __font(X1,Y1,12,Text,fontcolor,X2,Y2) return Widgets[Na].info[1] def __EndButton(Na): try: if type(Widgets[Na].info)==list: if Widgets[Na].info[0]=='button': Widgets[Na].info[1]=False except KeyError: pass #this button may not yet be defined def __TextInput(X,Y,W,Na,Tx=''): global Widgets,HitDefs,pw,ph global AllowHitUpdates #positioning precalculations pwW = pw*W ph20 = ph*20 #Widget init info if Na not in Widgets.keys(): Widgets[Na]=__Widget(); Widgets[Na].info=[Tx,False] if AllowHitUpdates: HitDefs.update({Na:[X,Y,X+pwW,Y+ph20]}) #Widget logic if Widgets[Na].event.releaseL: Widgets[Na].info[1]=True #isActive = True State = Widgets[Na].info __GL.glBegin(__GL.GL_QUADS) __GL.glColor4f(1.0,1.0,1.0,0.25) __GL.glVertex2f(X,Y) __GL.glVertex2f(X+pwW,Y) __GL.glVertex2f(X+pwW,Y+ph20) __GL.glVertex2f(X,Y+ph20) __GL.glEnd() def __BrowseBar(X,Y,W,Na,Fn,Text=''): global pw,ph __TextInput(X,Y,W,Na+"_TextInput",Tx='') __Button(X+(pw*W),Y,X+(pw*(W+54)),Y+(ph*20),Na+"_Button",Text='Browse') #----------------------------------- #panel drawing functions ActiveModelTab=0 def __ModelPanel(): global pw,ph,ActiveModelTab #positioning precalculations pw210 = pw*210 ph62 = ph*62 ph41 = ph*41 ph21 = ph*21 ph20 = ph*20 #__ExPanel(pw*0,ph*21,pw*210,ph*h,1,'MODEL') MB0 = __Button(0.,ph21,pw210,ph41,"ModelManageSlot","Models",(230,230,230,255),True) MB1 = __Button(0.,(1.-ph41 if MB0 else ph*42), pw210,(1.-ph21 if MB0 else ph62),"ModelFeaturesSlot","Features",(230,230,230,255)) MB2 = __Button(0.,(1.-ph20 if MB0 or MB1 else ph*63), pw210,(1. if MB0 or MB1 else ph*83),"ModelExportSlot","Export",(230,230,230,255)) if MB0 and MB1: #switch logic if ActiveModelTab==0: ActiveModelTab=1; __EndButton("ModelManageSlot") else: ActiveModelTab=0; __EndButton("ModelFeaturesSlot") if MB0 and MB2: if ActiveModelTab==0: ActiveModelTab=2; __EndButton("ModelManageSlot") else: ActiveModelTab=0; __EndButton("ModelExportSlot") if MB1 and MB2: if ActiveModelTab==1: ActiveModelTab=2; __EndButton("ModelFeaturesSlot") else: ActiveModelTab=1; __EndButton("ModelExportSlot") #draw widgets based on the active button if MB0: if __Button(pw*50,ph62,pw*160,ph*82,"ModelImportButton","Import",(230,230,230,255)): __EndButton("ModelImportButton") if MB1: pass #library model handling here if MB2: pass #__BrowseBar(pw*10,ph*40,180) #Model Export Path ActiveAnimTab=0 def __AnimPanel(): global pw,ph,ActiveAnimTab #positioning precalculations pw210 = pw*210 ph62 = ph*62 ph41 = ph*41 ph21 = ph*21 ph20 = ph*20 #__ExPanel(pw*0,ph*21,pw*210,ph*h,1,'MODEL') AB0 = __Button(1.-pw210,ph21,1.,ph41,"AnimManageSlot","Animations",(230,230,230,255),True) AB1 = __Button(1.-pw210,(1.-ph41 if AB0 else ph*42), 1.,(1.-ph21 if AB0 else ph62),"AnimFeaturesSlot","Features",(230,230,230,255)) AB2 = __Button(1.-pw210,(1.-ph20 if AB0 or AB1 else ph*63), 1.,(1. if AB0 or AB1 else ph*83),"AnimExportSlot","Export",(230,230,230,255)) if AB0 and AB1: #switch logic if ActiveAnimTab==0: ActiveAnimTab=1; __EndButton("AnimManageSlot") else: ActiveAnimTab=0; __EndButton("AnimFeaturesSlot") if AB0 and AB2: if ActiveAnimTab==0: ActiveAnimTab=2; __EndButton("AnimManageSlot") else: ActiveAnimTab=0; __EndButton("AnimExportSlot") if AB1 and AB2: if ActiveAnimTab==1: ActiveAnimTab=2; __EndButton("AnimFeaturesSlot") else: ActiveAnimTab=1; __EndButton("AnimExportSlot") #draw widgets based on the active button if AB0: if __Button(1.-(pw*160),ph62,1.-(pw*50),ph*82,"AnimImportButton","Import",(230,230,230,255)): __EndButton("AnimImportButton") if AB1: pass if AB2: #__BrowseBar(pw*10,ph*40,180) #Model Export Path pass def __DisplayPanel(X1,X2): global pw,ph #positioning precalculations pwX1251 = pw*(X1+251) pwX1131 = pw*(X1+131) pwX111 = pw*(X1+11) ph81 = ph*81 ph56 = ph*56 ph31 = ph*31 VIEWER.TOGGLE_LIGHTING=__TButton(pwX111,ph31,'EnLight',True,'Lighting') VIEWER.TOGGLE_WIREFRAME=__TButton(pwX111,ph56,'EnWire',False,'Wireframe') VIEWER.TOGGLE_BONES=__DropBox(pwX111,ph81,100,'Draw Bones',['None','Standard','Overlay (X-Ray)'],0) #reversed drawing order here so fonts overlay properly if VIEWER.TOGGLE_3D==2: VIEWER.TOGGLE_3D_MODE[1]=[1./60,1./120][__DropBox(pwX1251,ph81,50,'Freq (WIP)',['60hz','120hz'],0)] if VIEWER.TOGGLE_3D==1: VIEWER.TOGGLE_3D_MODE[0]=__DropBox(pwX1251,ph81,50,'Colors',['R|GB','G|RB','B|RG'],0) VIEWER.TOGGLE_3D=__DropBox(pwX1131,ph81,100,'3D Drawing',['Off','Analglyph','Shutter'],0) VIEWER.TOGGLE_ORTHO=__DropBox(pwX1131,ph56,100,'Projection',['Perspective','Orthographic'],1) VIEWER.TOGGLE_GRID=[2 if VIEWER.TOGGLE_GRID>2 else VIEWER.TOGGLE_GRID,3,4][__DropBox(pwX1131,ph31,100,'Display',['Grid','Floor','Off'],0)] def __ControlPanel(X1,X2): global pw,ph pass #long var names won't easily get used OptionsUpdatePanelExpensionState=False; OptionsUpdatePanelButton=0 def __OprionsUpdatePanel(w,h): global pw,ph,OptionsUpdatePanelExpensionState,OptionsUpdatePanelButton PES=OptionsUpdatePanelExpensionState #short local name from long global name #positioning precalculations pw21 = pw*21 pw20 = pw*20 pw13 = pw*13 pw10 = pw*10 pw7 = pw*7 ph20 = ph*20 ph14 = ph*14 ph13 = ph*13 ph7 = ph*7 ph6 = ph*6 if PES: X1,Y1,X2,Y2=0.0,0.0,1.0,1.0-ph20 TX1,TY1,TX2,TY2=0.5-pw10,1.0-ph6,0.5+pw10,1.0-ph14 else: X1,Y1,X2,Y2=0.0,0.0,1.0,0.0 TX1,TY1,TX2,TY2=0.5-pw10,ph6,0.5+pw10,ph14 __GL.glBegin(__GL.GL_QUADS) __GL.glColor4f(0.5,0.5,0.5,0.8) #options toggle __GL.glVertex2f(X1,Y1); __GL.glVertex2f(X2,Y1); __GL.glVertex2f(X2,Y2); __GL.glVertex2f(X1,Y2) __GL.glVertex2f(X1,Y2); __GL.glVertex2f(X2-pw21,Y2); __GL.glVertex2f(X2-pw21,Y2+ph20); __GL.glVertex2f(X1,Y2+ph20) __GL.glVertex2f(X2-pw20,Y2); __GL.glVertex2f(X2,Y2); __GL.glVertex2f(X2,Y2+ph20); __GL.glVertex2f(X2-pw20,Y2+ph20) __GL.glEnd() __GL.glColor4f(0.0,0.0,0.0,0.2) __GL.glBegin(__GL.GL_TRIANGLES) __GL.glVertex2f(TX1,TY1); __GL.glVertex2f(TX2,TY1); __GL.glVertex2f(0.5,TY2) __GL.glEnd() if PES: if OptionsUpdatePanelButton==0: #options drawing: pass if OptionsUpdatePanelButton==1: #update drawing: __font(X1,Y1,12,"The Update system is still in development.",(0,0,0,255),X2,Y2) if __Button(X1,Y2,X2-pw21,Y2+ph20,"OptionsPanelToggleButton",""): if not OptionsUpdatePanelExpensionState: #open panel OptionsUpdatePanelExpensionState=True OptionsUpdatePanelButton=0 elif OptionsUpdatePanelButton==0: OptionsUpdatePanelExpensionState=False #close panel else: OptionsUpdatePanelButton=0 #switch to options __EndButton("OptionsPanelToggleButton") if __Button(X2-pw20,Y2,X2,Y2+ph20,"UpdatePanelToggleButton",""): if not OptionsUpdatePanelExpensionState: #open panel OptionsUpdatePanelExpensionState=True OptionsUpdatePanelButton=1 elif OptionsUpdatePanelButton==1: OptionsUpdatePanelExpensionState=False #close panel else: OptionsUpdatePanelButton=1 #switch to update __EndButton("UpdatePanelToggleButton") __GL.glBegin(__GL.GL_QUADS) __GL.glColor4f(1.0,0.25,0.25,0.65) #options toggle __GL.glVertex2f(X2-pw13,Y2+ph7); __GL.glVertex2f(X2-pw7,Y2+ph7); __GL.glVertex2f(X2-pw7,Y2+ph13); __GL.glVertex2f(X2-pw13,Y2+ph13) __GL.glEnd() return PES #----------------------------------- def __ExPanel(X1,Y1,X2,Y2,EB,Na,MX=0,MY=0,St=True): #returns current state for other panels global Widgets,HitDefs,pw,ph global AllowHitUpdates #positioning precalculations pw35 = pw*35 pw30 = pw*30 pw25 = pw*25 pw15 = pw*15 pw10 = pw*10 pw5 = pw*5 ph35 = ph*35 ph30 = ph*30 ph25 = ph*25 ph15 = ph*15 ph10 = ph*10 ph5 = ph*5 sx=X2-X1 sy=Y2-Y1 hsx=sx/2 hsy=sy/2 #Widget init info if Na not in Widgets.keys(): Widgets[Na]=__Widget() Widgets[Na].info=St #toggle state #Widget logic if Widgets[Na].event.releaseL: Widgets[Na].info=(False if Widgets[Na].info else True) State = Widgets[Na].info #60x15px rectangle if EB==0: #top EBX1,EBY1,EBX2,EBY2=(X1+hsx-pw30),Y1,(X1+hsx+pw30),Y1+ph15 TPX1,TPY1 = EBX1+pw25,EBY1+ph5; TPX2,TPY2 = EBX1+pw30,EBY1+ph10; TPX3,TPY3 = EBX1+pw35,EBY1+ph5 elif EB==1: #right EBX1,EBY1,EBX2,EBY2=X2-pw15,hsy-ph30,X2,hsy+ph30 TPX1,TPY1 = EBX1+pw10,EBY1+ph25; TPX2,TPY2 = EBX1+pw5,EBY1+ph30; TPX3,TPY3 = EBX1+pw10,EBY1+ph35 elif EB==2: #bottom EBX1,EBY1,EBX2,EBY2=(X1+hsx-pw30),Y2-ph15,(X1+hsx+pw30),Y2 TPX1,TPY1 = EBX1+pw25,EBY1+ph10; TPX2,TPY2 = EBX1+pw30,EBY1+ph5; TPX3,TPY3 = EBX1+pw35,EBY1+ph10 elif EB==3: #left EBX1,EBY1,EBX2,EBY2=X1,hsy-ph30,X1+pw15,hsy+ph30 TPX1,TPY1 = EBX1+pw5,EBY1+ph25; TPX2,TPY2 = EBX1+pw10,EBY1+ph30; TPX3,TPY3 = EBX1+pw5,EBY1+ph35 #is the panel expanded? if not State: if EB==0: #top Eq=sy-ph15; EBY1,EBY2=EBY1+Eq,EBY2+Eq TPY1,TPY2,TPY3=TPY1+(Eq+ph5),TPY2+(Eq-ph5),TPY3+(Eq+ph5) elif EB==1: #right Eq=sx-pw15; EBX1,EBX2=EBX1-Eq,EBX2-Eq TPX1,TPX2,TPX3=TPX1-(Eq+pw5),TPX2-(Eq-pw5),TPX3-(Eq+pw5) elif EB==2: #bottom Eq=sy-ph15; EBY1,EBY2=EBY1-Eq,EBY2-Eq TPY1,TPY2,TPY3=TPY1-(Eq+ph5),TPY2-(Eq-ph5),TPY3-(Eq+ph5) elif EB==3: #left Eq=sx-pw15; EBX1,EBX2=EBX1+Eq,EBX2+Eq TPX1,TPX2,TPX3=TPX1+(Eq+pw5),TPX2+(Eq-pw5),TPX3+(Eq+pw5) ''' __GL.glColor4f(0.5,0.5,0.5,0.8) __GL.glBegin(__GL.GL_QUADS) #(just the BG color behind the toggle button) __GL.glVertex2f(EBX1+MX,EBY1+MY) __GL.glVertex2f(EBX1+MX,EBY2+MY) __GL.glVertex2f(EBX2+MX,EBY2+MY) __GL.glVertex2f(EBX2+MX,EBY1+MY) __GL.glEnd() ''' if AllowHitUpdates: HitDefs.update({Na:[EBX1+MX,EBY1+MY,EBX2+MX,EBY2+MY]}) __GL.glColor4f(0.0,0.0,0.0,0.175) __GL.glBegin(__GL.GL_TRIANGLES) __GL.glVertex3f(TPX1+MX,TPY1+MY,0.01) __GL.glVertex3f(TPX2+MX,TPY2+MY,0.01) __GL.glVertex3f(TPX3+MX,TPY3+MY,0.01) __GL.glEnd() __GL.glBegin(__GL.GL_QUADS) __GL.glVertex3f(EBX1+MX,EBY1+MY,0.01) __GL.glVertex3f(EBX1+MX,EBY2+MY,0.01) __GL.glVertex3f(EBX2+MX,EBY2+MY,0.01) __GL.glVertex3f(EBX2+MX,EBY1+MY,0.01) __GL.glEnd() if State: __GL.glBegin(__GL.GL_QUADS) __GL.glColor4f(0.5,0.5,0.5,0.8) #model (left) panel __GL.glVertex3f(X1,Y1,0.0) __GL.glVertex3f(X1,Y2,0.0) __GL.glVertex3f(X2,Y2,0.0) __GL.glVertex3f(X2,Y1,0.0) __GL.glEnd() return State def __FrameCheck(): #where most of the widget-event state-logic happens. #the functions below "__DrawGUI" simply handle base-state functions #a frame must pass before the base state can be reverted (where this function comes in) global Widgets #we don't need to worry about hit-defs here (only 1 widget at a time can be operated) for WN,W in Widgets.items(): #check for a click event: (transfer click to hold) if W.event.clickL: W.event.clickL=False; W.event.holdL=True if W.event.clickM: W.event.clickM=False; W.event.holdM=True if W.event.clickR: W.event.clickR=False; W.event.holdR=True #check for a release event: (disable the hold-state) if W.event.releaseL: W.event.releaseL=False; W.event.holdL=False if W.event.releaseM: W.event.releaseM=False; W.event.holdM=False if W.event.releaseR: W.event.releaseR=False; W.event.holdR=False #check for a scroll event: if W.event.scrollU: W.event.scrollU=False if W.event.scrollD: W.event.scrollD=False doFrameCheck=False def __Click(b,x,y): global Widgets,HitDefs,doFrameCheck for WN,HD in HitDefs.items(): X1,Y1,X2,Y2=HD if X1<x<X2 and Y1<y<Y2: # Widget clicked if b==1: Widgets[WN].event.clickL=True; doFrameCheck=True if b==2: Widgets[WN].event.clickM=True; doFrameCheck=True if b==3: Widgets[WN].event.clickR=True; doFrameCheck=True #scrolling: if b==4: Widgets[WN].event.scrollU=True; doFrameCheck=True if b==5: Widgets[WN].event.scrollD=True; doFrameCheck=True def __Release(b,x,y): global Widgets,HitDefs,doFrameCheck for WN,HD in HitDefs.items(): X1,Y1,X2,Y2=HD if X1<x<X2 and Y1<y<Y2: # Widget clicked if b==1: Widgets[WN].event.releaseL=True; doFrameCheck=True if b==2: Widgets[WN].event.releaseM=True; doFrameCheck=True if b==3: Widgets[WN].event.releaseR=True; doFrameCheck=True #scrolling is managed by "__FrameCheck", so it's not needed here def __Motion(b,x,y,rx,ry): pass ''' def __CheckPos(x,y): #checks the new mouse position when moved import sys for name in W_HitDefs: #we want to concentrait on if we're over a hit area X1,Y1,X2,Y2 = W_HitDefs[name] #Hit Area #are we in the hit area of this widget? if X1<x<X2 and Y1<y<Y2: W_States[name][3]=True else: W_States[name][3]=False ''' def __KeyPress(k): global Widgets,HitDefs,doFrameCheck for WN,W in Widgets.items(): if W.event.allowKeys: Widgets[WN].event.keyPress=True; doFrameCheck=True Widgets[WN].key=k def __KeyRelease(k): pass lw,lh = 0,0 def __DrawGUI(w,h,RotMatrix): #called directly by the display function after drawing the scene global pw,ph,lw,lh,layer #the GUI is drawn over the scene by clearing the depth buffer #using floats will cause a more accurate edge-blur between panels when the screen is resized pw,ph=1./w,1./h #using ints won't look as pretty, but you won't need the extra multiplication (TODO: add in options) global HitDefs HitDefs = {} #clear the hitdefs to avoid improper activation __GL.glMatrixMode(__GL.GL_PROJECTION) __GL.glLoadIdentity() __GL.glOrtho(0.0, 1.0, 1.0, 0.0, -100, 100) #__GLU.gluOrtho2D(0.0, 1.0, 1.0, 0.0) __GL.glMatrixMode(__GL.GL_MODELVIEW) __GL.glClear( __GL.GL_DEPTH_BUFFER_BIT ) #__GL.glPolygonMode(__GL.GL_FRONT_AND_BACK,__GL.GL_FILL) __GL.glLoadIdentity() __GL.glBlendFunc(__GL.GL_SRC_ALPHA, __GL.GL_ONE_MINUS_SRC_ALPHA) __GL.glEnable(__GL.GL_BLEND) __GL.glEnable(__GL.GL_DEPTH_TEST) __GL.glDisable(__GL.GL_TEXTURE_2D) __GL.glDisable(__GL.GL_LIGHTING) #positioning precalculations pw211 = pw*211 pw210 = pw*210 pw105 = pw*105 ph150 = ph*150 ph21 = ph*21 M,A,D,C=False,False,False,False if not __OprionsUpdatePanel(w,h): M = __ExPanel(0.,ph21,pw210,1.,1,'MODEL') if M: __ModelPanel() A = __ExPanel(1.-pw210,ph21,1.,1.,3,'ANIM') if A: __AnimPanel() D = __ExPanel(pw211 if M else 0.,ph21,1.-(pw211 if A else 0.),ph150,2,'DSPL',(0. if M else pw105)+(0. if A else -pw105)) if D: __DisplayPanel(210 if M else 0,-210 if A else 0) C = __ExPanel(pw211 if M else 0.,1.-ph150,1.-(pw211 if A else 0.),1.,0,'CTRL',(0 if M else pw105)+(0 if A else -pw105)) if C: __ControlPanel(210 if M else 0,-210 if A else 0) __GL.glDisable(__GL.GL_BLEND) #__GL.glEnable(__GL.GL_DEPTH_TEST) #axis __GL.glLineWidth(1.0) __GL.glPushMatrix() __GL.glTranslatef(pw*(228 if M else 17),ph*(h-(167 if C else 17)),0) __GL.glScalef(pw*600,ph*600,1) __GL.glMultMatrixf(RotMatrix) __GL.glColor3f(1.0,0.0,0.0) __GL.glBegin(__GL.GL_LINES); __GL.glVertex3f(0.0,0.0,0.0); __GL.glVertex3f(0.02,0.0,0.0); __GL.glEnd() #X __GL.glTranslatef(0.0145,0.0,0.0); __GL.glRotatef(90, 0.0, 1.0, 0.0) #__GLUT.glutSolidCone(0.003, 0.011, 8, 1) __GL.glRotatef(-90, 0.0, 1.0, 0.0); __GL.glTranslatef(-0.0145,0.0,0.0) __GL.glColor3f(0.0,1.0,0.0) __GL.glBegin(__GL.GL_LINES); __GL.glVertex3f(0.0,0.0,0.0); __GL.glVertex3f(0.0,-0.02,0.0); __GL.glEnd() #Y __GL.glTranslatef(0.0,-0.0145,0.0); __GL.glRotatef(90, 1.0, 0.0, 0.0) #__GLUT.glutSolidCone(0.003, 0.011, 8, 1) __GL.glRotatef(-90, 1.0, 0.0, 0.0); __GL.glTranslatef(0.0,0.0145,0.0) __GL.glColor3f(0.0,0.0,1.0) __GL.glBegin(__GL.GL_LINES); __GL.glVertex3f(0.0,0.0,0.0); __GL.glVertex3f(0.0,0.0,0.02); __GL.glEnd() #Z __GL.glTranslatef(0.0,0.0,0.0145) #__GLUT.glutSolidCone(0.003, 0.011, 8, 1) __GL.glTranslatef(0.0,0.0,-0.0145) __GL.glColor3f(0.5,0.5,0.5) ; #__GLUT.glutSolidSphere(0.003, 8, 4) __GL.glPopMatrix() for lid in layer: layer[lid].draw() global doFrameCheck if doFrameCheck: __FrameCheck(); doFrameCheck=False __GL.glBlendFunc(__GL.GL_SRC_ALPHA, __GL.GL_ONE_MINUS_SRC_ALPHA) #reset to mormal for anything else def __initGUI(): __pyg.font.init()
{ "repo_name": "Universal-Model-Converter/UMC3.0a", "path": "dev tests and files/data (scrapped dev5 attempt)/GUI_last.py", "copies": "1", "size": "32956", "license": "mit", "hash": -278279484921126660, "line_mean": 34.590712743, "line_max": 142, "alpha_frac": 0.5989197718, "autogenerated": false, "ratio": 2.7084155161078236, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.38073352879078237, "avg_score": null, "num_lines": null }
#1 #v 0.001 import COMMON,sys; sys.path.append('data') #TODO: remove: from OpenGL.GL import * from OpenGL.GLU import * from OpenGL import GL as __GL, GLU as __GLU import ArcBall as __AB, pygame as __pyg from pygame.locals import * #TODO: localize from LOGGING import LOG as __LOG, WRITE_LOG as __WLOG #will be moved to GUI import GUI as __GUI global Libs; Libs=[ [], # MtlNodes [], # Images [], # Textures [], # Materials [["UMC_Def_Scene",[]]], # Scenes [], # Objects []] # Animations #toggles TOGGLE_FULLSCREEN=0 TOGGLE_ORTHO=1 TOGGLE_LIGHTING=1 TOGGLE_3D=0 TOGGLE_3D_MODE=[0,0] TOGGLE_WIREFRAME=0 TOGGLE_BONES=1 TOGGLE_GRID=2 #TOGGLE_REDRAW=False #display list definition variables: global __TOP_GRID,__SIDE_GRID,__FRONT_GRID,\ __QUAD_FLOOR,__LINE_FLOOR,\ __MODEL_DATA,__BONE_DATA #the bone data is seperate so it can be drawn over the model data (X-ray), or within the model data #(specified by clearing the depth buffer before drawing the bones) #local usage: width,height = 800,600 W,H = 800,600; __abt=__AB.ArcBallT(width,height) #Tcll5850: HOORAY! My very first working class in UMC. =D #this class deals with the matrix applied to the model-view transformation class __viewMatrixclass(): def __init__(self): #[SX, RZ,-RY, 0 #-RZ, SY, RX, 0 # RY,-RX, SZ, 0 # TX, TY, TZ, 1] import ArcBall as __AB #TODO: use global import self.__ID33=__AB.Matrix3fT self.__ID44=__AB.Matrix4fT self.reset() def reset(self): #called by key 9 self.X,self.Y,self.Z=0.0,0.0,0.0 self.RotMtx=self.__ID33() self._scale=0.1 self.rotate(10.0,350.0,0.0) #keeping this here for reference (when needed), #since this works flawlessly for matrix (not view) transformation ''' def translate(self,x,y,z): #matrix translation self.Matrix[3][0]+=(self.Matrix[0][0]*x)+(self.Matrix[1][0]*y)+(self.Matrix[2][0]*z) self.Matrix[3][1]+=(self.Matrix[0][1]*x)+(self.Matrix[1][1]*y)+(self.Matrix[2][1]*z) self.Matrix[3][2]+=(self.Matrix[0][2]*x)+(self.Matrix[1][2]*y)+(self.Matrix[2][2]*z) self.Matrix[3][3]+=(self.Matrix[0][3]*x)+(self.Matrix[1][3]*y)+(self.Matrix[2][3]*z) #matrix rotation: def __RotX(self,x): #rotate along X axis from math import sin, cos, pi cosx,sinx=cos(x/180.0*pi),sin(x/180.0*pi) var1,var2=self.RotMtx[1][0],self.RotMtx[2][0] self.RotMtx[1][0]=(var1*cosx) +(var2*sinx) self.RotMtx[2][0]=(var1*-sinx)+(var2*cosx) var1,var2=self.RotMtx[1][1],self.RotMtx[2][1] self.RotMtx[1][1]=(var1*cosx) +(var2*sinx) self.RotMtx[2][1]=(var1*-sinx)+(var2*cosx) var1,var2=self.RotMtx[1][2],self.RotMtx[2][2] self.RotMtx[1][2]=(var1*cosx) +(var2*sinx) self.RotMtx[2][2]=(var1*-sinx)+(var2*cosx) def __RotY(self,y): #rotate along Y axis from math import sin, cos, pi cosy,siny=cos(y/180.0*pi),sin(y/180.0*pi) var1,var2=self.RotMtx[0][0],self.RotMtx[2][0] self.RotMtx[0][0]=(var1*cosy)+(var2*-siny) self.RotMtx[2][0]=(var1*siny)+(var2*cosy) var1,var2=self.RotMtx[0][1],self.RotMtx[2][1] self.RotMtx[0][1]=(var1*cosy)+(var2*-siny) self.RotMtx[2][1]=(var1*siny)+(var2*cosy) var1,var2=self.RotMtx[0][2],self.RotMtx[2][2] self.RotMtx[0][2] =(var1*cosy)+(var2*-siny) self.RotMtx[2][2]=(var1*siny)+(var2*cosy) def __RotZ(self,z): #rotate along Z axis from math import sin, cos, pi cosz,sinz=cos(z/180.0*pi),sin(z/180.0*pi) var1,var2=self.RotMtx[0][0],self.RotMtx[1][0] self.RotMtx[0][0]=(var1*cosz) +(var2*sinz) self.RotMtx[1][0]=(var1*-sinz)+(var2*cosz) var1,var2=self.RotMtx[0][1],self.RotMtx[1][1] self.RotMtx[0][1]=(var1*cosz) +(var2*sinz) self.RotMtx[1][1]=(var1*-sinz)+(var2*cosz) var1,var2=self.RotMtx[0][2],self.RotMtx[1][2] self.RotMtx[0][2]=(var1*cosz) +(var2*sinz) self.RotMtx[1][2]=(var1*-sinz)+(var2*cosz) ''' def _getMtx(self): mtx=self.__ID44() #apply rotation mtx[0][0]=self.RotMtx[0][0] mtx[0][1]=self.RotMtx[0][1] mtx[0][2]=self.RotMtx[0][2] mtx[1][0]=self.RotMtx[1][0] mtx[1][1]=self.RotMtx[1][1] mtx[1][2]=self.RotMtx[1][2] mtx[2][0]=self.RotMtx[2][0] mtx[2][1]=self.RotMtx[2][1] mtx[2][2]=self.RotMtx[2][2] #apply rotation to translation and apply translation import COMMON #Tcll5850: yes I'm using UMC scripting functions... bite me ir=COMMON.MtxInvert(mtx) #inverse rotation mtx[3][0]=(ir[0][0]*self.X)+(ir[0][1]*self.Y)+(ir[0][2]*self.Z) mtx[3][1]=(ir[1][0]*self.X)+(ir[1][1]*self.Y)+(ir[1][2]*self.Z) mtx[3][2]=(ir[2][0]*self.X)+(ir[2][1]*self.Y)+(ir[2][2]*self.Z) #apply scale and return the result mtx[0][0] *= self._scale; mtx[1][0] *= self._scale; mtx[2][0] *= self._scale mtx[0][1] *= self._scale; mtx[1][1] *= self._scale; mtx[2][1] *= self._scale mtx[0][2] *= self._scale; mtx[1][2] *= self._scale; mtx[2][2] *= self._scale mtx[0][3] *= self._scale; mtx[1][3] *= self._scale; mtx[2][3] *= self._scale mtx[3][0] *= self._scale; mtx[3][1] *= self._scale; mtx[3][2] *= self._scale return mtx def translate(self,x,y,z): #modify the matrix translation (from view) X=(self.RotMtx[0][0]*x)+(self.RotMtx[0][1]*y)+(self.RotMtx[0][2]*z) Y=(self.RotMtx[1][0]*x)+(self.RotMtx[1][1]*y)+(self.RotMtx[1][2]*z) Z=(self.RotMtx[2][0]*x)+(self.RotMtx[2][1]*y)+(self.RotMtx[2][2]*z) X/=self._scale; Y/=self._scale; Z/=self._scale self.X+=X; self.Y+=Y; self.Z+=Z def rotate(self,x=0.0,y=0.0,z=0.0): #modify the matrix rotation (from view) from math import sin,cos,radians import ArcBall as __AB cosx = cos(radians(x)); sinx = sin(radians(x)) cosy = cos(radians(y)); siny = sin(radians(y)) cosz = cos(radians(z)); sinz = sin(radians(z)) m = self.__ID33() m[0][0] = cosy * cosz m[0][1] = sinz * cosy m[0][2] = -siny m[1][0] = (sinx * cosz * siny - cosx * sinz) m[1][1] = (sinx * sinz * siny + cosz * cosx) m[1][2] = sinx * cosy; m[2][0] = (sinx * sinz + cosx * cosz * siny) m[2][1] = (cosx * sinz * siny - sinx * cosz) m[2][2] = cosx * cosy self.RotMtx = __AB.Matrix3fMulMatrix3f(self.RotMtx,m) def mtxrotate(self,mtx33): #modify the matrix rotation (from view) self.RotMtx=mtx33 def scale(self,s): #modify the matrix scale (applied to view when calling the main matrix) self._scale*=s def getaxismtx(self): #a transformation matrix designed specifically for the GUI axis display rm=self.__ID44() rm[0][0]=self.RotMtx[0][0] rm[0][1]=self.RotMtx[0][1]*-1 rm[0][2]=self.RotMtx[0][2] rm[1][0]=self.RotMtx[1][0]*-1 rm[1][1]=self.RotMtx[1][1] rm[1][2]=self.RotMtx[1][2]*-1 rm[2][0]=self.RotMtx[2][0] rm[2][1]=self.RotMtx[2][1]*-1 rm[2][2]=self.RotMtx[2][2] return rm __viewMatrix = __viewMatrixclass() #all viewing transformations are applied to the view-matrix... #this matrix is applied to the modelview matrix before drawing the models #this saves performance since the calculations don't have to be recalculated for every frame # however, calling __viewMatrix._getMtx() builds the matrix from internal eular values before returning it. # (it's fast, but could be slightly faster (save the last matrix for re-use until updated)) ''' def __if2f(i): return (i*0.003921568627450980392156862745098 if type(i)==int else i) #__if2f(255) >>> 1.0 from FORMAT import UMC_POINTS,UMC_LINES,UMC_LINESTRIP,UMC_LINELOOP,UMC_TRIANGLES,UMC_TRIANGLESTRIP,UMC_TRIANGLEFAN,UMC_QUADS,UMC_QUADSTRIP,UMC_POLYGON __UMCGLPRIMITIVES = { UMC_POINTS:__GL.GL_POINTS, UMC_LINES:__GL.GL_LINES, UMC_LINESTRIP:__GL.GL_LINE_STRIP, UMC_LINELOOP:__GL.GL_LINE_LOOP, UMC_TRIANGLES:__GL.GL_TRIANGLES, UMC_TRIANGLESTRIP:__GL.GL_TRIANGLE_STRIP, UMC_TRIANGLEFAN:__GL.GL_TRIANGLE_FAN, UMC_QUADS:__GL.GL_QUADS, UMC_QUADSTRIP:__GL.GL_QUAD_STRIP, UMC_POLYGON:__GL.GL_POLYGON} def __M(): global Libs,__UMCGLPRIMITIVES __GL.glColor3f(1.0,1.0,1.0) for Name,Objects in Libs[4]: for ID in Objects: ObjectName,Viewport,LRS,Sub_Data,Parent_ID=Libs[5][ID] SDType,SDName,SDData1,SDData2=Sub_Data if SDType=="_Mesh": __GL.glLineWidth(1.0) MaterialName,MatNodeID,MatColors,Textures,R1,R2 = Libs[3][SDData1] if type(SDData1)==int else [ "UMC_Def_Mat", '', [[1.0,1.0,1.0,1.0],[1.0,1.0,1.0,1.0],[0.5,0.5,0.5,1.0],[0.0,0.0,0.0,0.0],25.0], [], [], [] ] MAR,MAG,MAB,MAA = MatColors[0] MDR,MDG,MDB,MDA = MatColors[1] MSR,MSG,MSB,MSA = MatColors[2] MER,MEG,MEB,MEA = MatColors[3] MSV = MatColors[4] __GL.glMaterialfv(__GL.GL_FRONT, __GL.GL_AMBIENT, [MAR,MAG,MAB,MAA]) __GL.glMaterialfv(__GL.GL_FRONT, __GL.GL_DIFFUSE, [MDR,MDG,MDB,MDA]); __GL.glMaterialfv(__GL.GL_FRONT, __GL.GL_SPECULAR, [MSR,MSG,MSB,MSA]); __GL.glMaterialfv(__GL.GL_FRONT, __GL.GL_EMISSION, [MER,MEG,MEB,MEA]) __GL.glMaterialf(__GL.GL_FRONT, __GL.GL_SHININESS, MSV) ## # Create Texture ## __GL.glBindTexture(__GL.GL_TEXTURE_2D, __GL.glGenTextures(1)) # 2d texture (x and y size) ## __GL.glPixelStorei(__GL.GL_UNPACK_ALIGNMENT,1) ## __GL.glTexImage2D(__GL.GL_TEXTURE_2D, 0, 3, ix, iy, 0, __GL.GL_RGBA, __GL.GL_UNSIGNED_BYTE, image) ## __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) ## __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_T, __GL.GL_CLAMP) ## __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_REPEAT) ## __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_T, __GL.GL_REPEAT) ## __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_MAG_FILTER, __GL.GL_NEAREST) ## __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_MIN_FILTER, __GL.GL_NEAREST) ## __GL.glTexEnvf(__GL.GL_TEXTURE_ENV, __GL.GL_TEXTURE_ENV_MODE, __GL.GL_DECAL) Verts,Normals,Colors,UVs,Weights,Primitives=SDData2 LC0,LC1=[0,0,0,0],[0,0,0,0] #Remember last used colors (starts at transparent black) for Primitive,Facepoints in Primitives: __GL.glBegin(__UMCGLPRIMITIVES[Primitive]) for V,N,Cs,Us in Facepoints: C0,C1=Cs; U0,U1,U2,U3,U4,U5,U6,U7=Us #once I support materials properly: (materials hold textures) #if U0!='': glMultiTexCoord2f(GL_TEXTURE0,Fl(UVs[0][U0][0]),Fl(UVs[0][U0][1])) #if U1!='': glMultiTexCoord2f(GL_TEXTURE1,Fl(UVs[1][U1][0]),Fl(UVs[1][U1][1])) #if U2!='': glMultiTexCoord2f(GL_TEXTURE2,Fl(UVs[2][U2][0]),Fl(UVs[2][U2][1])) #if U3!='': glMultiTexCoord2f(GL_TEXTURE3,Fl(UVs[3][U3][0]),Fl(UVs[3][U3][1])) #if U4!='': glMultiTexCoord2f(GL_TEXTURE4,Fl(UVs[4][U4][0]),Fl(UVs[4][U4][1])) #if U5!='': glMultiTexCoord2f(GL_TEXTURE5,Fl(UVs[5][U5][0]),Fl(UVs[5][U5][1])) #if U6!='': glMultiTexCoord2f(GL_TEXTURE6,Fl(UVs[6][U6][0]),Fl(UVs[6][U6][1])) #if U7!='': glMultiTexCoord2f(GL_TEXTURE7,Fl(UVs[7][U7][0]),Fl(UVs[7][U7][1])) #max texture is 31 if C0!='': #IRAGBA format C0L=len(Colors[0][C0]) C0R,C0G,C0B,C0A=[__if2f(Colors[0][C0][0]), __if2f(Colors[0][C0][1]) if C0L>2 else __if2f(Colors[0][C0][0]), __if2f(Colors[0][C0][2]) if C0L>2 else __if2f(Colors[0][C0][0]), __if2f(Colors[0][C0][3]) if C0L==4 else (__if2f(Colors[0][C0][1]) if C0L==2 else 1.0)] __GL.glColor4f((MAR+MDR+C0R)/3,(MAG+MDG+C0G)/3,(MAB+MDB+C0B)/3,(MAA+MDA+C0A)/3) __GL.glMaterialfv(GL_FRONT, GL_AMBIENT, [(MAR+C0R)/2,(MAG+C0G)/2,(MAB+C0B)/2,(MAA+C0A)/2]) __GL.glMaterialfv(GL_FRONT, GL_DIFFUSE, [(MDR+C0R)/2,(MDG+C0G)/2,(MDB+C0B)/2,(MDA+C0A)/2]) __GL.glMaterialfv(GL_FRONT, GL_SPECULAR, [(MSR+C0R)/2,(MSG+C0G)/2,(MSB+C0B)/2,(MSA+C0A)/2]) __GL.glMaterialf(GL_FRONT, GL_SHININESS, 25.0) LC0=[C0R,C0G,C0B,C0A] if C1!='': #IRAGBA format C1L=len(Colors[1][C1]) C1R,C1G,C1B,C1A=[__if2f(Colors[1][C1][0]), __if2f(Colors[1][C1][1]) if C1L>2 else __if2f(Colors[1][C1][0]), __if2f(Colors[1][C1][2]) if C1L>2 else __if2f(Colors[1][C1][0]), __if2f(Colors[1][C1][3]) if C1L==4 else (__if2f(Colors[1][C1][1]) if C1L==2 else 1.0)] if LC1!=[C1R,C1G,C1B,C1A]: __GL.glSecondaryColor3f(C1R,C1G,C1B); LC1=[C1R,C1G,C1B,C1A] #Alpha is supported but not registered here (glSecondaryColor4f is not a registered function) if N!='': __GL.glNormal3f(Normals[N][0]*0.1,Normals[N][1]*0.1,Normals[N][2]*0.1) VL=len(Verts[V]) VX,VY,VZ=Verts[V]+([0.0] if VL==2 else []) __GL.glVertex3f(VX,VY,VZ) __GL.glEnd() elif SDType=="_DMesh": pass def __B(): global Libs for Name,Objects in Libs[4]: for ID in Objects: ObjectName,Viewport,LRS,Sub_Data,Parent_ID=Libs[5][ID] SDType,SDName,SDData1,SDData2=Sub_Data if SDType=="_Rig": __GL.glLineWidth(3.5) for bone in SDData2: PLRS,CLRS = (SDData2[bone[4]][2] if type(bone[4])==int else [0,0,0,0,0,0,1,1,1]),bone[2] __GL.glBegin(GL_LINES) __GL.glColor3f(1,1,1) __GL.glVertex3f((PLRS[0]*PLRS[6]),(PLRS[1]*PLRS[7]),(PLRS[2]*PLRS[8])) __GL.glVertex3f((CLRS[0]*CLRS[6]),(CLRS[1]*CLRS[7]),(CLRS[2]*CLRS[8])) __GL.glEnd() ''' def __Draw_Scene(): global TOGGLE_FULLSCREEN,TOGGLE_LIGHTING,TOGGLE_3D,TOGGLE_WIREFRAME,TOGGLE_BONES,TOGGLE_ORTHO global __viewMatrix __GL.glMultMatrixf(__viewMatrix._getMtx()) __GL.glDisable(__GL.GL_LIGHTING) #disable for the grid if TOGGLE_GRID<4: global __TOP_GRID,__SIDE_GRID,__FRONT_GRID,__QUAD_FLOOR __GL.glCallList([__TOP_GRID,__SIDE_GRID,__FRONT_GRID,__QUAD_FLOOR][TOGGLE_GRID]) ''' if TOGGLE_LIGHTING: __GL.glEnable(__GL.GL_LIGHTING) __GL.glCallList(__GL.__MODEL_DATA) #finally got display lists working =D if TOGGLE_LIGHTING: __GL.glDisable(__GL.GL_LIGHTING) #disable for the grid and bones if TOGGLE_BONES: if TOGGLE_BONES==2: __GL.glClear( __GL.GL_DEPTH_BUFFER_BIT ) #overlay the bones (X-Ray) __GL.glCallList(__BONE_DATA) for Name,Objects in Libs[4]: #de-scaled bone joints for ID in Objects: ObjectName,Viewport,LRS,Sub_Data,Parent_ID=Libs[5][ID] SDType,SDName,SDData1,SDData2=Sub_Data if SDType=="_Rig": for bone in SDData2: PLRS,CLRS = (SDData2[bone[4]][2] if type(bone[4])==int else [0,0,0,0,0,0,1,1,1]),bone[2] __GL.glTranslate((CLRS[0]*CLRS[6]),(CLRS[1]*CLRS[7]),(CLRS[2]*CLRS[8])) #glutSolidSphere(0.03/__viewMatrix._scale, 25, 25) __GL.glTranslate(-(CLRS[0]*CLRS[6]),-(CLRS[1]*CLRS[7]),-(CLRS[2]*CLRS[8])) ''' pass #___________________________________________________________________________________________ _mode=0 #logger mode: 0=write, 1=append DIR='' #to remember the import directory def Keyboard(key, x, y): global TOGGLE_FULLSCREEN,TOGGLE_LIGHTING,TOGGLE_GRID,TOGGLE_WIREFRAME,TOGGLE_BONES,TOGGLE_3D,TOGGLE_ORTHO global _mode,DIR global __MODEL_DATA,__BONE_DATA #//--// need a GUI handler for these if key == chr(9): #import model typenames,modules,modnames,ihandlers,decmpr = [],[],[],[],[]; iftypes,isupport = [],[] for M,D,I in COMMON.__Scripts[0][0]: #get model import scripts if D[1] != ('',['']): #script has model info (not sure if it's safe to remove this yet) iftypes+=[(D[1][0],tuple(["*.%s"%T for T in D[1][1]]))] for T in D[1][1]: try: isupport.index("*.%s"%T) #is this file type already supported? except: isupport+=["*.%s"%T] #add the current file type to the supported types list modnames+=[D[1][0]] #displayed in the GUI or Tk fiter typenames+=[T] #filetype modules+=[M] #current script ihandlers+=[I] #included image handlers #----- Tkinter dialog (will be replaced) _in=askopenfilename(title='Import Model', filetypes=[('Supported', " ".join(isupport))]+iftypes) #----- if _in=='': pass #action cancelled else: COMMON.__functions=[0,0,0,0] #prevent unwanted initialization #this block will change once I use my own dialog #Tkinter doesn't return the filter ID #----- it = _in.split('.')[-1] if typenames.count(it)>1: print '\nThis filetype is used by multiple scripts:\n' scr = [] for idx,ft in enumerate(typenames): if ft==it: scr+=[[modnames[idx],modules[idx]]] for I,NM in enumerate(scr): print ' %i - %s'%(I,NM[0]) print sid=input('Please enter the script ID here: ') i=__import__(scr[sid][1]) else: ti=typenames.index(it) i=__import__(modules[ti]) COMMON.__ReloadScripts() #check for valid changes to the scripts #----- try: #can we get our hands on the file? COMMON.ImportFile(_in,1) #set the file data global Libs; __Libs=Libs #remember last session in case of a script error Libs=[[],[],[],[],[["Def_Scene",[]]],[]] #reset the data for importing print 'Converting from import format...' try: #does the script contain any unfound errors? __LOG('-- importing %s --\n'%_in.split('/')[-1]) i.ImportModel(it,None) print 'Verifying data...' glNewList(__MODEL_DATA, GL_COMPILE); __M(); glEndList() glNewList(__BONE_DATA, GL_COMPILE); __B(); glEndList() print 'Updating Viewer\n' glutSetWindowTitle("Universal Model Converter v3.0a (dev5) - %s" % _in.split('/')[-1]) #export UMC session data l=open('session.ses','w') l.write(str([1,Libs])) l.close() COMMON.__ClearFiles() #clear the file data to be used for writing except: Libs=__Libs print "Error! Check 'session-info.log' for more details.\n" import traceback typ,val,tb=sys.exc_info()#;tb=traceback.extract_tb(i[2])[0] traceback.print_exception( typ,val,tb#, #limit=2, #file=sys.stdout ) print __Libs=[] #save memory usage except: pass #an error should already be thrown __WLOG(0) #write log COMMON.__CleanScripts() #remove pyc files if key == chr(5): #export model COMMON.__ClearFiles() #clear the file data again... just in case etypenames,emodules,emodnames,ehandlers = [],[],[],[]; eftypes = [] for M,D,I in COMMON.__Scripts[0][1]: if D[1] != ('',['']): #has model info eftypes+=[(D[1][0],tuple(["*.%s"%T for T in D[1][1]]))] for T in D[1][1]: emodnames+=[D[1][0]] etypenames+=[T] emodules+=[M] ehandlers+=[I] #Tkinter dialog (will be replaced) #----- _en=asksaveasfilename(title='Export Model', filetypes=eftypes, defaultextension='.ses') #----- if _en=='': pass else: COMMON.__functions=[0,0,0,0] #prevent unwanted initialization #this block will change once I use my own dialog #Tkinter doesn't return the filter ID #----- et = _en.split('.')[-1] if etypenames.count(et)>1: print '\nThis filetype is used by multiple scripts:\n' scr = [] for idx,ft in enumerate(etypenames): if ft==et: scr+=[[emodnames[idx],emodules[idx]]] for I,NM in enumerate(scr): print ' %i - %s'%(I,NM[0]) print sid=input('Please enter the script ID here: ') e=__import__(scr[sid][1]) else: e=__import__(emodules[etypenames.index(et)]) COMMON.__ReloadScripts() #check for valid changes to the scripts #----- ''' try: COMMON.ExportFile(_en) #add the file to the data space print 'converting to export format...' e.ExportModel(et,None) COMMON.__WriteFiles() print 'Done!' except: print "Error! Check 'session-info.log' for details.\n" ''' COMMON.ExportFile(_en) #add the file to the data space print 'converting to export format...' e.ExportModel(et,None) COMMON.__WriteFiles() print 'Refreshing Viewer\n' #''' __WLOG(_mode) #write log COMMON.__CleanScripts() #remove pyc files #//--// #___________________________________________________________________________________________ def __SDLVResize(W,H, VMODE): #A limitation of SDL (the GL context also needs to be reset with the screen) __pyg.display.set_mode((W,H), VMODE) #DspInf = __pyg.display.Info() #UI display lists: global __TOP_GRID,__SIDE_GRID,__FRONT_GRID,__QUAD_FLOOR,__LINE_FLOOR,__MODEL_DATA,__BONE_DATA def G(D): __GL.glLineWidth(1.0) GS=60; i0,i1 = (D+1 if D<2 else 0),(D-1 if D>0 else 2) C1,C2,A1,A2,nA1,nA2=[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0] C1[D],C2[i0]=1,1 A1[D],A2[i0]=GS,GS; nA1[D],nA2[i0]= -GS,-GS S1,iS1=A1,A1;S2,iS2=A2,A2; nS1,niS1=nA1,nA1;nS2,niS2=nA2,nA2 __GL.glBegin(__GL.GL_LINES) __GL.glColor3fv(C1);__GL.glVertex3f(A1[0],A1[1],A1[2]);__GL.glVertex3f(nA1[0],nA1[1],nA1[2]) __GL.glColor3fv(C2);__GL.glVertex3f(A2[0],A2[1],A2[2]);__GL.glVertex3f(nA2[0],nA2[1],nA2[2]) __GL.glColor3f(0.5,0.5,0.5) s=0 while s < GS: s+=10; S1[i0],nS1[i0],S2[D],nS2[D]=s,s,s,s __GL.glVertex3f(S1[0],S1[1],S1[2]);__GL.glVertex3f(nS1[0],nS1[1],nS1[2]) __GL.glVertex3f(S2[0],S2[1],S2[2]);__GL.glVertex3f(nS2[0],nS2[1],nS2[2]) iS1[i0],niS1[i0],iS2[D],niS2[D]=-s,-s,-s,-s __GL.glVertex3f(iS1[0],iS1[1],iS1[2]);__GL.glVertex3f(niS1[0],niS1[1],niS1[2]) __GL.glVertex3f(iS2[0],iS2[1],iS2[2]);__GL.glVertex3f(niS2[0],niS2[1],niS2[2]) __GL.glEnd() def F(D): __GL.glLineWidth(1.0) def quad(p1,p2): __GL.glVertex3f(p1+2.5,0,p2+2.5); __GL.glVertex3f(p1+2.5,0,p2-2.5) __GL.glVertex3f(p1-2.5,0,p2-2.5); __GL.glVertex3f(p1-2.5,0,p2+2.5) FS=40; clr=0.3125; p1=0 while p1 < FS: clr=(0.3125 if clr==0.5 else 0.5); p2=0 while p2 < FS: __GL.glColor3f(clr,clr,clr) if D: #draw lines so you can actually see the floor __GL.glBegin(__GL.GL_LINE_LOOP); quad(p1,p2); __GL.glEnd() __GL.glBegin(__GL.GL_LINE_LOOP); quad(p1,-p2); __GL.glEnd() __GL.glBegin(__GL.GL_LINE_LOOP); quad(-p1,-p2); __GL.glEnd() __GL.glBegin(__GL.GL_LINE_LOOP); quad(-p1,p2); __GL.glEnd() #TODO: this draws lines for every quad instead of just the outside quads #^a performance killer >_> else: __GL.glBegin(__GL.GL_QUADS) quad(p1,p2); quad(p1,-p2) quad(-p1,p2); quad(-p1,-p2) __GL.glEnd() p2+=5; clr=(0.3125 if clr==0.5 else 0.5) p1+=5 __FRONT_GRID = __GL.glGenLists(1); __GL.glNewList(__FRONT_GRID, __GL.GL_COMPILE); G(2); __GL.glEndList() __SIDE_GRID = __GL.glGenLists(1); __GL.glNewList(__SIDE_GRID, __GL.GL_COMPILE); G(1); __GL.glEndList() __TOP_GRID = __GL.glGenLists(1); __GL.glNewList(__TOP_GRID, __GL.GL_COMPILE); G(0); __GL.glEndList() __QUAD_FLOOR = __GL.glGenLists(1); __GL.glNewList(__QUAD_FLOOR, __GL.GL_COMPILE); F(0); __GL.glEndList() __LINE_FLOOR = __GL.glGenLists(1); __GL.glNewList(__LINE_FLOOR, __GL.GL_COMPILE); F(1); __GL.glEndList() __MODEL_DATA = __GL.glGenLists(1); __BONE_DATA = __GL.glGenLists(1) __GL.glClearColor(0.13, 0.13, 0.13, 1.0) __GL.glClearDepth(1.0) #TODO: need to manage these more efficiently: __GL.glEnable(__GL.GL_DEPTH_TEST) __GL.glDepthFunc(__GL.GL_LEQUAL) __GL.glEnable(__GL.GL_LIGHTING) __GL.glEnable(__GL.GL_LIGHT0) __GL.glEnable(__GL.GL_NORMALIZE) #scale normals when model is scaled __GL.glDisable(__GL.GL_BLEND) #disabled for models __GL.glBlendFunc(__GL.GL_SRC_ALPHA, __GL.GL_ONE_MINUS_SRC_ALPHA) __GL.glShadeModel(__GL.GL_SMOOTH) #__GUI.__ResizeGUI(W,H) def Init(): VIDEOMODE = OPENGL|DOUBLEBUF|RESIZABLE #VIDEOMODE&=~RESIZABLE __pyg.display.init() icon = __pyg.Surface((1,1)); icon.set_alpha(255) __pyg.display.set_icon(icon) __pyg.display.set_caption("Universal Model Converter v3.0a (dev5)") global width,height __SDLVResize(width,height, VIDEOMODE) __pyg.joystick.init() joy = [__pyg.joystick.Joystick(j) for j in range(__pyg.joystick.get_count())] for j in joy: j.init() #__GUI.__initGUI() global W,H; LW,LH=W,H #restored screen size (coming from full-screen) global TOGGLE_FULLSCREEN,TOGGLE_LIGHTING,TOGGLE_GRID,TOGGLE_WIREFRAME,TOGGLE_BONES,TOGGLE_3D,TOGGLE_ORTHO MODS=0 #Modifier keys (global use) [ Alt(4)[0b100] | Ctrl(2)[0b10] | Shift(1)[0b1] ] __lastRot = __AB.Matrix3fT() #last updated rotation (ArcBall view rotation) O = 0.025 # eye translation offset EYE=None #3D L or R EYE (for Shutter method) while True: ''' line=0 for axis in range(GCNJS.get_numaxes()): #sys.stdout.write("axis%i: %s\n"%(axis,str(GCNJS.get_axis(axis)))) GCNJS.get_axis(axis) line+=1 for hat in range(GCNJS.get_numhats()): #sys.stdout.write("hat%i: %s\n"%(hat,str(GCNJS.get_hat(hat)))) GCNJS.get_hat(hat) line+=1 for button in range(GCNJS.get_numbuttons()): #sys.stdout.write("button%i: %s\n"%(button,str(GCNJS.get_button(button)))) GCNJS.get_button(button) line+=1 #sys.stdout.write('%s'%('\r'*line)) ''' for i,e in enumerate(__pyg.event.get()): if e.type == QUIT: __pyg.display.quit(); return None #VIEWER.init() >>> None if e.type == ACTIVEEVENT: pass #e.gain; e.state if e.type == KEYDOWN: #e.key; e.mod #__GUI.__KeyPress(e.key) if e.key==K_RSHIFT or e.key==K_LSHIFT: MODS|=0b001 if e.key==K_RCTRL or e.key==K_LCTRL: MODS|=0b010 if e.key==K_RALT or e.key==K_LALT: MODS|=0b100 if e.key not in [K_RSHIFT,K_LSHIFT,K_RCTRL,K_LCTRL,K_RALT,K_LALT]: TOGGLE_GRID=(2 if TOGGLE_GRID<3 else TOGGLE_GRID) #don't let MODS affect the grid if e.key==K_KP5: #__GUI.Widgets['Projection'].info[0]=[1,0][#__GUI.Widgets['Projection'].info[0]] #change widget state #TOGGLE_ORTHO = __GUI.Widgets['Projection'].info[0] #verify TOGGLE_ORTHO if panel is closed TOGGLE_ORTHO = 0 if TOGGLE_ORTHO else 1 if e.key==K_KP9: #reset the view if MODS==0: __viewMatrix.mtxrotate(__AB.Matrix3fT()) #rotation __viewMatrix.rotate(10.0,350.0,0.0) elif MODS&0b001: __viewMatrix.X=0.0;__viewMatrix.Y=0.0;__viewMatrix.Z=0.0 #translation elif MODS&0b010: __viewMatrix._scale=0.1 #scale elif MODS&0b100: __viewMatrix.reset() #everything if e.key==K_KP8: #rotate/translate U if MODS&0b001: __viewMatrix.translate(0.0,-0.25,0.0) else: __viewMatrix.rotate(5.0,0.0,0.0) if e.key==K_KP2: #rotate/translate D if MODS&0b001: __viewMatrix.translate(0.0,0.25,0.0) else: __viewMatrix.rotate(-5.0,0.0,0.0) if e.key==K_KP4: #rotate/translate L if MODS&0b001: __viewMatrix.translate(0.25,0.0,0.0) else: __viewMatrix.rotate(0.0,5.0,0.0) if e.key==K_KP6: #rotate/translate R if MODS&0b001: __viewMatrix.translate(-0.25,0.0,0.0) else: __viewMatrix.rotate(0.0,-5.0,0.0) #//--// kept as an added option if e.key==K_KP_PLUS: __viewMatrix.scale(1.1) if e.key==K_KP_MINUS: __viewMatrix.scale(1/1.1) #//--// if e.key==K_KP1: #front view TOGGLE_GRID=(0 if TOGGLE_GRID<3 else TOGGLE_GRID) __viewMatrix.mtxrotate(__AB.Matrix3fT()) #reset the rotation using a minor bug if MODS&0b010: __viewMatrix.rotate(0.0,180.0,0.0) #back View if e.key==K_KP3: TOGGLE_GRID=(1 if TOGGLE_GRID<3 else TOGGLE_GRID) __viewMatrix.mtxrotate(__AB.Matrix3fT()) #reset the rotation if MODS&0b010: __viewMatrix.rotate(0.0,90.0,0.0) #right-side View else: __viewMatrix.rotate(0.0,-90.0,0.0) #left-side view if e.key==K_KP7: TOGGLE_GRID=(2 if TOGGLE_GRID<3 else TOGGLE_GRID) __viewMatrix.mtxrotate(__AB.Matrix3fT()) #reset the rotation if MODS&0b010: __viewMatrix.rotate(-90.0,0.0,0.0) #bottom View else: __viewMatrix.rotate(90.0,0.0,0.0) #top view if e.key==K_ESCAPE: if TOGGLE_FULLSCREEN: TOGGLE_FULLSCREEN=0 VIDEOMODE&=~FULLSCREEN VIDEOMODE|=RESIZABLE W,H = LW,LH else: TOGGLE_FULLSCREEN=1 VIDEOMODE&=~RESIZABLE VIDEOMODE|=FULLSCREEN LW,LH=W,H; W,H = 1280,1024 __SDLVResize(W,H, VIDEOMODE) __abt.setBounds(W,H) if e.type == KEYUP: #e.key; e.mod #__GUI.__KeyRelease(e.key) if e.key==K_RSHIFT or e.key==K_LSHIFT: MODS&=0b110 if e.key==K_RCTRL or e.key==K_LCTRL: MODS&=0b101 if e.key==K_RALT or e.key==K_LALT: MODS&=0b011 if e.type == MOUSEBUTTONDOWN: #e.pos; e.button x,y=e.pos #__GUI.__Click(e.button,(1./W)*x,(1./H)*y) #GUI if e.button==2: __lastRot=__viewMatrix.RotMtx __abt.click(__AB.Point2fT(x,y)) else: __lastRot=__viewMatrix.RotMtx if e.button==4: if MODS==0: __viewMatrix.scale(1.1) elif MODS&0b001: __viewMatrix.translate(0.0,0.25,0.0) #translate Y elif MODS&0b010: __viewMatrix.translate(0.25,0.0,0.0) #translate X elif e.button==5: if MODS==0: __viewMatrix.scale(1/1.1) elif MODS&0b001: __viewMatrix.translate(0.0,-0.25,0.0) #translate Y elif MODS&0b010: __viewMatrix.translate(-0.25,0.0,0.0) #translate X if e.type == MOUSEBUTTONUP: #e.pos; e.button x,y=e.pos #__GUI.__Release(e.button,(1./W)*x,(1./H)*y) if e.button==2: __lastRot=__viewMatrix.RotMtx if e.type == MOUSEMOTION: #e.pos; e.rel; e.buttons x,y = e.pos; rx,ry = e.rel #__GUI.__Motion(e.buttons,x,y,rx,ry) #GUI if e.buttons[1]: #MMB view rotation (like blender24) if MODS&0b001: s = __viewMatrix._scale tx = ((1./W)*rx)/s ty = ((1./H)*-ry)/s __viewMatrix.translate(tx,ty,0.0) elif MODS&0b010: s = ry __viewMatrix.scale(s) else: __viewMatrix.mtxrotate( __AB.Matrix3fMulMatrix3f( __lastRot, #get our previous view rot matrix __AB.Matrix3fSetRotationFromQuat4f(__abt.drag(__AB.Point2fT(x,y))) #get a rot matrix from the mouse position ) #multiply the matrices ) #update the view matrix with the new rotation if TOGGLE_GRID<3 and TOGGLE_GRID!=2: TOGGLE_GRID=2 if e.type == JOYAXISMOTION: #e.joy; e.axis; e.value pass #print 'Joy:',e.joy, ', Axis:',e.axis, ', Value:',e.value if e.type == JOYBALLMOTION: pass #e.joy; e.ball; e.rel if e.type == JOYHATMOTION: #e.joy; e.hat; e.value pass #print 'Joy:',e.joy, ', Hat:',e.hat, ', Value:',e.value if e.type == JOYBUTTONDOWN: #e.joy; e.button pass #print 'Joy:',e.joy, ', Button:',e.button if e.type == JOYBUTTONUP: pass #e.joy; e.button if e.type == VIDEORESIZE: #e.size; e.w; e.h _w,_h = e.size if _w+_h>0 and _h>0: W,H=_w,_h __SDLVResize(W,H, VIDEOMODE) __abt.setBounds(W,H) if e.type == VIDEOEXPOSE: pass if e.type == USEREVENT: pass #e.code #Display: __GL.glViewport(0, 0, W, H) __GL.glMatrixMode(__GL.GL_MODELVIEW) __GL.glLoadIdentity() __GL.glClear(__GL.GL_COLOR_BUFFER_BIT|__GL.GL_DEPTH_BUFFER_BIT) __GL.glPushMatrix() __GL.glLightfv(__GL.GL_LIGHT0, __GL.GL_POSITION, ( 1.5, 1.5, 2.0, 0.0 )) __GL.glPolygonMode(__GL.GL_FRONT_AND_BACK,(__GL.GL_LINE if TOGGLE_WIREFRAME else __GL.GL_FILL)) if TOGGLE_3D==1: #Analglyph __GL.glDrawBuffer( __GL.GL_BACK_LEFT ) #not really sure why this is needed, #but the code doesn't work if removed... #L Eye (2 colors) if TOGGLE_3D_MODE[0]==0: __GL.glColorMask( 1,0,0,1 ) elif TOGGLE_3D_MODE[0]==1: __GL.glColorMask( 0,1,0,1 ) elif TOGGLE_3D_MODE[0]==2: __GL.glColorMask( 0,0,1,1 ) __GL.glClear( __GL.GL_COLOR_BUFFER_BIT | __GL.GL_DEPTH_BUFFER_BIT ) __GL.glLoadIdentity(); __GL.glTranslate(O,0.0,0.0) __Draw_Scene() #R Eye (1 color) if TOGGLE_3D_MODE[0]==0: __GL.glColorMask( 0,1,1,1 ) #doesn't overlay if TOGGLE_3D_MODE[0]==1: __GL.glColorMask( 1,0,1,1 ) if TOGGLE_3D_MODE[0]==2: __GL.glColorMask( 1,1,0,1 ) __GL.glClear( __GL.GL_DEPTH_BUFFER_BIT ) __GL.glLoadIdentity(); __GL.glTranslate(-O*2,0.0,0.0) __Draw_Scene() __GL.glColorMask( 1,1,1,1 ) #restore the color mask for later drawing elif TOGGLE_3D==2: #Shutter (need a better method than simply rotating between frames) #does not require quad-buffered hardware. (I might add error-detection-support for this later) #... if your machine supports this, it should greatly improve visual performance quality ;) EYE=(-O if EYE==O else O) __viewMatrix.translate(EYE,0.0,0.0) __Draw_Scene() else: __Draw_Scene() #no 3D display __GL.glPopMatrix() #__GUI.__DrawGUI(__viewMatrix.getaxismtx()) __GL.glMatrixMode(__GL.GL_PROJECTION) __GL.glLoadIdentity() P=float(W)/float(H) if TOGGLE_ORTHO: __GL.glOrtho(-2*P, 2*P, -2, 2, -100, 100) else: __GLU.gluPerspective(43.6025, P, 1, 100.0); __GLU.gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) #gluLookAt( eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz) #glOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near, GLdouble far) #glFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near, GLdouble far) #gluPerspective(GLdouble fovy, GLdouble aspect, GLdouble near, GLdouble far) __pyg.display.flip() Init()
{ "repo_name": "Universal-Model-Converter/UMC3.0a", "path": "dev tests and files/data (scrapped dev5 attempt)/VIEWER.py", "copies": "1", "size": "38649", "license": "mit", "hash": -388916875545100900, "line_mean": 44.4171562867, "line_max": 223, "alpha_frac": 0.5161323708, "autogenerated": false, "ratio": 2.877168167944614, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.38933005387446135, "avg_score": null, "num_lines": null }
#1 #v 0.001 import sys; #sys.path.append('data') import COMMON #TODO: remove: from OpenGL.GL import * from OpenGL.GLU import * from OpenGL import GL as __GL, GLU as __GLU import Python.ArcBall as __AB, pygame as __pyg from pygame.locals import * #TODO: localize from tkFileDialog import askopenfilename,asksaveasfilename from LOGGING import LOG as __LOG, WRITE_LOG as __WLOG #will be moved to GUI import GUI as __GUI import FORMAT as __FORMAT global Libs; Libs=[ [], # Reserved [], # Reserved [["UMC_Def_Scene",[]]], # Scenes [], # Objects [], # Materials [], # Material Add-ins [], # Textures []] # Images #toggles TOGGLE_FULLSCREEN=0 TOGGLE_ORTHO=True TOGGLE_LIGHTING=1 TOGGLE_3D=0 TOGGLE_3D_MODE=[0,0] TOGGLE_WIREFRAME=0 TOGGLE_BONES=1 TOGGLE_GRID=2 TOGGLE_NORMALS=0 #TOGGLE_REDRAW=False #display list definition variables: global __TOP_GRID,__SIDE_GRID,__FRONT_GRID,\ __QUAD_FLOOR,__LINE_FLOOR,\ __MODEL_DATA,__NORMAL_DATA,__BONE_DATA #the bone data is seperate so it can be drawn over the model data (X-ray), or within the model data #(specified by clearing the depth buffer before drawing the bones) #local usage: width,height = 800.,600. W,H = 800.,600.; __abt=__AB.ArcBallT(width,height) #copied from COMMON cause this doesn't exist in COMMON 9_9 def MtxInvert(Mtx): det = Mtx[0][3]*Mtx[1][2]*Mtx[2][1]*Mtx[3][0] - Mtx[0][2]*Mtx[1][3]*Mtx[2][1]*Mtx[3][0] - \ Mtx[0][3]*Mtx[1][1]*Mtx[2][2]*Mtx[3][0] + Mtx[0][1]*Mtx[1][3]*Mtx[2][2]*Mtx[3][0] + \ Mtx[0][2]*Mtx[1][1]*Mtx[2][3]*Mtx[3][0] - Mtx[0][1]*Mtx[1][2]*Mtx[2][3]*Mtx[3][0] - \ Mtx[0][3]*Mtx[1][2]*Mtx[2][0]*Mtx[3][1] + Mtx[0][2]*Mtx[1][3]*Mtx[2][0]*Mtx[3][1] + \ Mtx[0][3]*Mtx[1][0]*Mtx[2][2]*Mtx[3][1] - Mtx[0][0]*Mtx[1][3]*Mtx[2][2]*Mtx[3][1] - \ Mtx[0][2]*Mtx[1][0]*Mtx[2][3]*Mtx[3][1] + Mtx[0][0]*Mtx[1][2]*Mtx[2][3]*Mtx[3][1] + \ Mtx[0][3]*Mtx[1][1]*Mtx[2][0]*Mtx[3][2] - Mtx[0][1]*Mtx[1][3]*Mtx[2][0]*Mtx[3][2] - \ Mtx[0][3]*Mtx[1][0]*Mtx[2][1]*Mtx[3][2] + Mtx[0][0]*Mtx[1][3]*Mtx[2][1]*Mtx[3][2] + \ Mtx[0][1]*Mtx[1][0]*Mtx[2][3]*Mtx[3][2] - Mtx[0][0]*Mtx[1][1]*Mtx[2][3]*Mtx[3][2] - \ Mtx[0][2]*Mtx[1][1]*Mtx[2][0]*Mtx[3][3] + Mtx[0][1]*Mtx[1][2]*Mtx[2][0]*Mtx[3][3] + \ Mtx[0][2]*Mtx[1][0]*Mtx[2][1]*Mtx[3][3] - Mtx[0][0]*Mtx[1][2]*Mtx[2][1]*Mtx[3][3] - \ Mtx[0][1]*Mtx[1][0]*Mtx[2][2]*Mtx[3][3] + Mtx[0][0]*Mtx[1][1]*Mtx[2][2]*Mtx[3][3] return[[( Mtx[1][2]*Mtx[2][3]*Mtx[3][1] - Mtx[1][3]*Mtx[2][2]*Mtx[3][1] + Mtx[1][3]*Mtx[2][1]*Mtx[3][2] - Mtx[1][1]*Mtx[2][3]*Mtx[3][2] - Mtx[1][2]*Mtx[2][1]*Mtx[3][3] + Mtx[1][1]*Mtx[2][2]*Mtx[3][3]) /det, ( Mtx[0][3]*Mtx[2][2]*Mtx[3][1] - Mtx[0][2]*Mtx[2][3]*Mtx[3][1] - Mtx[0][3]*Mtx[2][1]*Mtx[3][2] + Mtx[0][1]*Mtx[2][3]*Mtx[3][2] + Mtx[0][2]*Mtx[2][1]*Mtx[3][3] - Mtx[0][1]*Mtx[2][2]*Mtx[3][3]) /det, ( Mtx[0][2]*Mtx[1][3]*Mtx[3][1] - Mtx[0][3]*Mtx[1][2]*Mtx[3][1] + Mtx[0][3]*Mtx[1][1]*Mtx[3][2] - Mtx[0][1]*Mtx[1][3]*Mtx[3][2] - Mtx[0][2]*Mtx[1][1]*Mtx[3][3] + Mtx[0][1]*Mtx[1][2]*Mtx[3][3]) /det, ( Mtx[0][3]*Mtx[1][2]*Mtx[2][1] - Mtx[0][2]*Mtx[1][3]*Mtx[2][1] - Mtx[0][3]*Mtx[1][1]*Mtx[2][2] + Mtx[0][1]*Mtx[1][3]*Mtx[2][2] + Mtx[0][2]*Mtx[1][1]*Mtx[2][3] - Mtx[0][1]*Mtx[1][2]*Mtx[2][3]) /det], [( Mtx[1][3]*Mtx[2][2]*Mtx[3][0] - Mtx[1][2]*Mtx[2][3]*Mtx[3][0] - Mtx[1][3]*Mtx[2][0]*Mtx[3][2] + Mtx[1][0]*Mtx[2][3]*Mtx[3][2] + Mtx[1][2]*Mtx[2][0]*Mtx[3][3] - Mtx[1][0]*Mtx[2][2]*Mtx[3][3]) /det, ( Mtx[0][2]*Mtx[2][3]*Mtx[3][0] - Mtx[0][3]*Mtx[2][2]*Mtx[3][0] + Mtx[0][3]*Mtx[2][0]*Mtx[3][2] - Mtx[0][0]*Mtx[2][3]*Mtx[3][2] - Mtx[0][2]*Mtx[2][0]*Mtx[3][3] + Mtx[0][0]*Mtx[2][2]*Mtx[3][3]) /det, ( Mtx[0][3]*Mtx[1][2]*Mtx[3][0] - Mtx[0][2]*Mtx[1][3]*Mtx[3][0] - Mtx[0][3]*Mtx[1][0]*Mtx[3][2] + Mtx[0][0]*Mtx[1][3]*Mtx[3][2] + Mtx[0][2]*Mtx[1][0]*Mtx[3][3] - Mtx[0][0]*Mtx[1][2]*Mtx[3][3]) /det, ( Mtx[0][2]*Mtx[1][3]*Mtx[2][0] - Mtx[0][3]*Mtx[1][2]*Mtx[2][0] + Mtx[0][3]*Mtx[1][0]*Mtx[2][2] - Mtx[0][0]*Mtx[1][3]*Mtx[2][2] - Mtx[0][2]*Mtx[1][0]*Mtx[2][3] + Mtx[0][0]*Mtx[1][2]*Mtx[2][3]) /det], [( Mtx[1][1]*Mtx[2][3]*Mtx[3][0] - Mtx[1][3]*Mtx[2][1]*Mtx[3][0] + Mtx[1][3]*Mtx[2][0]*Mtx[3][1] - Mtx[1][0]*Mtx[2][3]*Mtx[3][1] - Mtx[1][1]*Mtx[2][0]*Mtx[3][3] + Mtx[1][0]*Mtx[2][1]*Mtx[3][3]) /det, ( Mtx[0][3]*Mtx[2][1]*Mtx[3][0] - Mtx[0][1]*Mtx[2][3]*Mtx[3][0] - Mtx[0][3]*Mtx[2][0]*Mtx[3][1] + Mtx[0][0]*Mtx[2][3]*Mtx[3][1] + Mtx[0][1]*Mtx[2][0]*Mtx[3][3] - Mtx[0][0]*Mtx[2][1]*Mtx[3][3]) /det, ( Mtx[0][1]*Mtx[1][3]*Mtx[3][0] - Mtx[0][3]*Mtx[1][1]*Mtx[3][0] + Mtx[0][3]*Mtx[1][0]*Mtx[3][1] - Mtx[0][0]*Mtx[1][3]*Mtx[3][1] - Mtx[0][1]*Mtx[1][0]*Mtx[3][3] + Mtx[0][0]*Mtx[1][1]*Mtx[3][3]) /det, ( Mtx[0][3]*Mtx[1][1]*Mtx[2][0] - Mtx[0][1]*Mtx[1][3]*Mtx[2][0] - Mtx[0][3]*Mtx[1][0]*Mtx[2][1] + Mtx[0][0]*Mtx[1][3]*Mtx[2][1] + Mtx[0][1]*Mtx[1][0]*Mtx[2][3] - Mtx[0][0]*Mtx[1][1]*Mtx[2][3]) /det], [( Mtx[1][2]*Mtx[2][1]*Mtx[3][0] - Mtx[1][1]*Mtx[2][2]*Mtx[3][0] - Mtx[1][2]*Mtx[2][0]*Mtx[3][1] + Mtx[1][0]*Mtx[2][2]*Mtx[3][1] + Mtx[1][1]*Mtx[2][0]*Mtx[3][2] - Mtx[1][0]*Mtx[2][1]*Mtx[3][2]) /det, ( Mtx[0][1]*Mtx[2][2]*Mtx[3][0] - Mtx[0][2]*Mtx[2][1]*Mtx[3][0] + Mtx[0][2]*Mtx[2][0]*Mtx[3][1] - Mtx[0][0]*Mtx[2][2]*Mtx[3][1] - Mtx[0][1]*Mtx[2][0]*Mtx[3][2] + Mtx[0][0]*Mtx[2][1]*Mtx[3][2]) /det, ( Mtx[0][2]*Mtx[1][1]*Mtx[3][0] - Mtx[0][1]*Mtx[1][2]*Mtx[3][0] - Mtx[0][2]*Mtx[1][0]*Mtx[3][1] + Mtx[0][0]*Mtx[1][2]*Mtx[3][1] + Mtx[0][1]*Mtx[1][0]*Mtx[3][2] - Mtx[0][0]*Mtx[1][1]*Mtx[3][2]) /det, ( Mtx[0][1]*Mtx[1][2]*Mtx[2][0] - Mtx[0][2]*Mtx[1][1]*Mtx[2][0] + Mtx[0][2]*Mtx[1][0]*Mtx[2][1] - Mtx[0][0]*Mtx[1][2]*Mtx[2][1] - Mtx[0][1]*Mtx[1][0]*Mtx[2][2] + Mtx[0][0]*Mtx[1][1]*Mtx[2][2]) /det]] #Tcll5850: HOORAY! My very first working class in UMC. =D #this class deals with the matrix applied to the model-view transformation class __viewMatrixclass(): def __init__(self): #[SX, RZ,-RY, 0 #-RZ, SY, RX, 0 # RY,-RX, SZ, 0 # TX, TY, TZ, 1] import Python.ArcBall as __AB #TODO: use global import self.__ID33=__AB.Matrix3fT self.__ID44=__AB.Matrix4fT self.reset() def reset(self): #called by key 9 self.X,self.Y,self.Z=0.0,0.0,0.0 self.RotMtx=self.__ID33() self._scale=0.1 self.rotate(10.0,350.0,0.0) #keeping this here for reference (when needed), #since this works flawlessly for matrix (not view) transformation ''' def translate(self,x,y,z): #matrix translation self.Matrix[3][0]+=(self.Matrix[0][0]*x)+(self.Matrix[1][0]*y)+(self.Matrix[2][0]*z) self.Matrix[3][1]+=(self.Matrix[0][1]*x)+(self.Matrix[1][1]*y)+(self.Matrix[2][1]*z) self.Matrix[3][2]+=(self.Matrix[0][2]*x)+(self.Matrix[1][2]*y)+(self.Matrix[2][2]*z) self.Matrix[3][3]+=(self.Matrix[0][3]*x)+(self.Matrix[1][3]*y)+(self.Matrix[2][3]*z) #matrix rotation: def __RotX(self,x): #rotate along X axis from math import sin, cos, pi cosx,sinx=cos(x/180.0*pi),sin(x/180.0*pi) var1,var2=self.RotMtx[1][0],self.RotMtx[2][0] self.RotMtx[1][0]=(var1*cosx) +(var2*sinx) self.RotMtx[2][0]=(var1*-sinx)+(var2*cosx) var1,var2=self.RotMtx[1][1],self.RotMtx[2][1] self.RotMtx[1][1]=(var1*cosx) +(var2*sinx) self.RotMtx[2][1]=(var1*-sinx)+(var2*cosx) var1,var2=self.RotMtx[1][2],self.RotMtx[2][2] self.RotMtx[1][2]=(var1*cosx) +(var2*sinx) self.RotMtx[2][2]=(var1*-sinx)+(var2*cosx) def __RotY(self,y): #rotate along Y axis from math import sin, cos, pi cosy,siny=cos(y/180.0*pi),sin(y/180.0*pi) var1,var2=self.RotMtx[0][0],self.RotMtx[2][0] self.RotMtx[0][0]=(var1*cosy)+(var2*-siny) self.RotMtx[2][0]=(var1*siny)+(var2*cosy) var1,var2=self.RotMtx[0][1],self.RotMtx[2][1] self.RotMtx[0][1]=(var1*cosy)+(var2*-siny) self.RotMtx[2][1]=(var1*siny)+(var2*cosy) var1,var2=self.RotMtx[0][2],self.RotMtx[2][2] self.RotMtx[0][2] =(var1*cosy)+(var2*-siny) self.RotMtx[2][2]=(var1*siny)+(var2*cosy) def __RotZ(self,z): #rotate along Z axis from math import sin, cos, pi cosz,sinz=cos(z/180.0*pi),sin(z/180.0*pi) var1,var2=self.RotMtx[0][0],self.RotMtx[1][0] self.RotMtx[0][0]=(var1*cosz) +(var2*sinz) self.RotMtx[1][0]=(var1*-sinz)+(var2*cosz) var1,var2=self.RotMtx[0][1],self.RotMtx[1][1] self.RotMtx[0][1]=(var1*cosz) +(var2*sinz) self.RotMtx[1][1]=(var1*-sinz)+(var2*cosz) var1,var2=self.RotMtx[0][2],self.RotMtx[1][2] self.RotMtx[0][2]=(var1*cosz) +(var2*sinz) self.RotMtx[1][2]=(var1*-sinz)+(var2*cosz) ''' def _getMtx(self): mtx=self.__ID44() #apply rotation mtx[0][0]=self.RotMtx[0][0] mtx[0][1]=self.RotMtx[0][1] mtx[0][2]=self.RotMtx[0][2] mtx[1][0]=self.RotMtx[1][0] mtx[1][1]=self.RotMtx[1][1] mtx[1][2]=self.RotMtx[1][2] mtx[2][0]=self.RotMtx[2][0] mtx[2][1]=self.RotMtx[2][1] mtx[2][2]=self.RotMtx[2][2] #apply rotation to translation and apply translation #import COMMON #Tcll5850: yes I'm using UMC scripting functions... bite me ir=MtxInvert(mtx) #inverse rotation mtx[3][0]=(ir[0][0]*self.X)+(ir[0][1]*self.Y)+(ir[0][2]*self.Z) mtx[3][1]=(ir[1][0]*self.X)+(ir[1][1]*self.Y)+(ir[1][2]*self.Z) mtx[3][2]=(ir[2][0]*self.X)+(ir[2][1]*self.Y)+(ir[2][2]*self.Z) #apply scale and return the result mtx[0][0] *= self._scale; mtx[1][0] *= self._scale; mtx[2][0] *= self._scale mtx[0][1] *= self._scale; mtx[1][1] *= self._scale; mtx[2][1] *= self._scale mtx[0][2] *= self._scale; mtx[1][2] *= self._scale; mtx[2][2] *= self._scale mtx[0][3] *= self._scale; mtx[1][3] *= self._scale; mtx[2][3] *= self._scale mtx[3][0] *= self._scale; mtx[3][1] *= self._scale; mtx[3][2] *= self._scale return mtx def translate(self,x,y,z): #modify the matrix translation (from view) X=(self.RotMtx[0][0]*x)+(self.RotMtx[0][1]*y)+(self.RotMtx[0][2]*z) Y=(self.RotMtx[1][0]*x)+(self.RotMtx[1][1]*y)+(self.RotMtx[1][2]*z) Z=(self.RotMtx[2][0]*x)+(self.RotMtx[2][1]*y)+(self.RotMtx[2][2]*z) X/=self._scale; Y/=self._scale; Z/=self._scale self.X+=X; self.Y+=Y; self.Z+=Z def rotate(self,x=0.0,y=0.0,z=0.0): #modify the matrix rotation (from view) from math import sin,cos,radians import Python.ArcBall as __AB cosx = cos(radians(x)); sinx = sin(radians(x)) cosy = cos(radians(y)); siny = sin(radians(y)) cosz = cos(radians(z)); sinz = sin(radians(z)) m = self.__ID33() m[0][0] = cosy * cosz m[0][1] = sinz * cosy m[0][2] = -siny m[1][0] = (sinx * cosz * siny - cosx * sinz) m[1][1] = (sinx * sinz * siny + cosz * cosx) m[1][2] = sinx * cosy; m[2][0] = (sinx * sinz + cosx * cosz * siny) m[2][1] = (cosx * sinz * siny - sinx * cosz) m[2][2] = cosx * cosy self.RotMtx = __AB.Matrix3fMulMatrix3f(self.RotMtx,m) def mtxrotate(self,mtx33): #modify the matrix rotation (from view) self.RotMtx=mtx33 def scale(self,s): #modify the matrix scale (applied to view when calling the main matrix) self._scale*=s def getaxismtx(self): #a transformation matrix designed specifically for the GUI axis display rm=self.__ID44() rm[0][0]=self.RotMtx[0][0] rm[0][1]=self.RotMtx[0][1]*-1 rm[0][2]=self.RotMtx[0][2] rm[1][0]=self.RotMtx[1][0]*-1 rm[1][1]=self.RotMtx[1][1] rm[1][2]=self.RotMtx[1][2]*-1 rm[2][0]=self.RotMtx[2][0] rm[2][1]=self.RotMtx[2][1]*-1 rm[2][2]=self.RotMtx[2][2] return rm __viewMatrix = __viewMatrixclass() #all viewing transformations are applied to the view-matrix... #this matrix is applied to the modelview matrix before drawing the models #this saves performance since the calculations don't have to be recalculated for every frame # however, calling __viewMatrix._getMtx() builds the matrix from internal eular values before returning it. # (it's fast, but could be slightly faster (save the last matrix for re-use until updated)) def __if2f(i): return (i*0.003921568627450980392156862745098 if type(i)==int else i) #__if2f(255) >>> 1.0 from FORMAT import UMC_POINTS,UMC_LINES,UMC_LINESTRIP,UMC_LINELOOP,UMC_TRIANGLES,UMC_TRIANGLESTRIP,UMC_TRIANGLEFAN,UMC_QUADS,UMC_QUADSTRIP,UMC_POLYGON __UMCGLPRIMITIVES = { UMC_POINTS:__GL.GL_POINTS, UMC_LINES:__GL.GL_LINES, UMC_LINESTRIP:__GL.GL_LINE_STRIP, UMC_LINELOOP:__GL.GL_LINE_LOOP, UMC_TRIANGLES:__GL.GL_TRIANGLES, UMC_TRIANGLESTRIP:__GL.GL_TRIANGLE_STRIP, UMC_TRIANGLEFAN:__GL.GL_TRIANGLE_FAN, UMC_QUADS:__GL.GL_QUADS, UMC_QUADSTRIP:__GL.GL_QUAD_STRIP, UMC_POLYGON:__GL.GL_POLYGON} __GL_TEX = {} def __M(): global Libs,__UMCGLPRIMITIVES,__GL_TEX,__MODEL_DATA __GL.glEnable(__GL.GL_TEXTURE_2D) __GL.glDeleteTextures(__GL_TEX.values()) __GL_TEX.clear() #define textures here __GL.glPixelStorei(__GL.GL_UNPACK_ALIGNMENT,1) for ImageName,ImageW,ImageH,ImagePixels,ImageColors in Libs[7]: image = bytearray() if len(ImageColors)==0: ImageFormat = len(ImagePixels[0])-1 #I, IA, RGB, or RGBA format for IRAGBA in ImagePixels: image += bytearray(IRAGBA) else: ImageFormat = len(ImageColors[0])-1 #I, IA, RGB, or RGBA format for I in ImagePixels: image += bytearray(ImageColors[I]) __GL_TEX[ImageName] = __GL.glGenTextures(1) __GL.glBindTexture(__GL.GL_TEXTURE_2D, __GL_TEX[ImageName] ) __GL.glTexParameteri(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_MAG_FILTER, __GL.GL_LINEAR) __GL.glTexParameteri(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_MIN_FILTER, __GL.GL_LINEAR) _IFMT = [__GL.GL_RGB, __GL.GL_RGBA, __GL.GL_RGB, __GL.GL_RGBA][ImageFormat] _PXFMT = [__GL.GL_LUMINANCE,__GL.GL_LUMINANCE_ALPHA,__GL.GL_RGB,__GL.GL_RGBA][ImageFormat] __GL.glTexImage2D(__GL.GL_TEXTURE_2D, 0, _IFMT, ImageW, ImageH, 0, _PXFMT, __GL.GL_UNSIGNED_BYTE, str(image)) __GL.glDisable(__GL.GL_TEXTURE_2D) #generate Model Display-List here __MODEL_DATA = __GL.glGenLists(1) __GL.glNewList(__MODEL_DATA, __GL.GL_COMPILE) __GL.glColor3f(1.0,1.0,1.0) for SceneName,SceneObjects in Libs[2]: for ObjectID in SceneObjects: ObjectName,ObjectViewport,ObjectLRS,ObjectSubData,ObjectParentID=Libs[3][ObjectID] SubDataType,SubDataName,SubDataData1,SubDataData2=ObjectSubData if SubDataType=="_Mesh": __GL.glLineWidth(1.0) MaterialName,MaterialTEVs,MaterialColors,MaterialTextures,R1,R2 = Libs[4][SubDataData1] if type(SubDataData1)==int else [ "UMC_Def_Mat", '', [[1.0,1.0,1.0,1.0],[1.0,1.0,1.0,1.0],[0.5,0.5,0.5,1.0],[0.0,0.0,0.0,0.0],25.0], [], [], [] ] MAR,MAG,MAB,MAA = MaterialColors[0] #Ambient MDR,MDG,MDB,MDA = MaterialColors[1] #Diffuse MSR,MSG,MSB,MSA = MaterialColors[2] #Specular MER,MEG,MEB,MEA = MaterialColors[3] #Emmisive MSV = MaterialColors[4] #Shininess C0R,C0G,C0B,C0A= (MAR+MDR)/2,(MAG+MDG)/2,(MAB+MDB)/2,(MAA+MDA)/2 MeshVerts,MeshNormals,MeshColors,MeshUVs,MeshWeights,MeshPrimitives=SubDataData2 #call from pre-defined textures here for TextureID in MaterialTextures: TextureName,TextureParams,TextureEnvParams,TextureR1,TextureImageName,TextureR2 = Libs[6][TextureID] # Apply Texture(s) __GL.glBindTexture(__GL.GL_TEXTURE_2D, __GL_TEX[TextureImageName] ) ''' __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_T, __GL.GL_CLAMP) ''' __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_REPEAT) __GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_T, __GL.GL_REPEAT) #''' #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_MAG_FILTER, __GL.GL_LINEAR) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_MIN_FILTER, __GL.GL_LINEAR) break #only use the first for now #notes: #__GL.glTexEnvf(__GL.GL_TEXTURE_ENV, __GL.GL_TEXTURE_ENV_MODE, __GL.GL_MODULATE) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_DEPTH_STENCIL_TEXTURE_MODE, # [__GL.GL_DEPTH_COMPONENT, __GL.GL_STENCIL_COMPONENT][T0]) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_BASE_LEVEL, int(T1)) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_BORDER_COLOR, [R,G,B,A]) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_COMPARE_FUNC, # [__GL.GL_CLAMP][T3]) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) #__GL.glTexParameterf(__GL.GL_TEXTURE_2D, __GL.GL_TEXTURE_WRAP_S, __GL.GL_CLAMP) ''' glTexParameterf( GL_TEXTURE_1D, GL_TEXTURE_2D, GL_TEXTURE_3D, GL_TEXTURE_1D_ARRAY, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_RECTANGLE, GL_TEXTURE_CUBE_MAP , GL_DEPTH_STENCIL_TEXTURE_MODE, GL_TEXTURE_BASE_LEVEL, GL_TEXTURE_BORDER_COLOR, GL_TEXTURE_COMPARE_FUNC, GL_TEXTURE_COMPARE_MODE, GL_TEXTURE_LOD_BIAS, GL_TEXTURE_MIN_FILTER, GL_TEXTURE_MAG_FILTER, GL_TEXTURE_MIN_LOD, GL_TEXTURE_MAX_LOD, GL_TEXTURE_MAX_LEVEL, GL_TEXTURE_SWIZZLE_R, GL_TEXTURE_SWIZZLE_G, GL_TEXTURE_SWIZZLE_B, GL_TEXTURE_SWIZZLE_A, GL_TEXTURE_SWIZZLE_RGBA, GL_TEXTURE_WRAP_S, GL_TEXTURE_WRAP_T, GL_TEXTURE_WRAP_R , GL_DEPTH_STENCIL_TEXTURE_MODE: GL_DEPTH_COMPONENT, GL_STENCIL_COMPONENT GL_TEXTURE_BASE_LEVEL: int(MipMap) GL_TEXTURE_BORDER_COLOR: [R,G,B,A] GL_TEXTURE_COMPARE_FUNC: GL_LEQUAL, GL_GEQUAL, GL_LESS, GL_GREATER, GL_EQUAL, GL_NOTEQUAL, GL_ALWAYS, GL_NEVER #NOTE: GL_TEXTURE_COMPARE_MODE = GL_COMPARE_REF_TO_TEXTURE GL_TEXTURE_COMPARE_MODE: GL_COMPARE_REF_TO_TEXTURE, GL_NONE GL_TEXTURE_LOD_BIAS: float(Bias) GL_TEXTURE_MIN_FILTER: GL_NEAREST, GL_LINEAR, GL_NEAREST_MIPMAP_NEAREST GL_LINEAR_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_LINEAR GL_TEXTURE_MAG_FILTER: GL_NEAREST, GL_LINEAR GL_TEXTURE_MIN_LOD: -1000 GL_TEXTURE_MAX_LOD: 1000 GL_TEXTURE_MAX_LEVEL: 1000 GL_TEXTURE_SWIZZLE_R: GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA, GL_ZERO, GL_ONE GL_TEXTURE_SWIZZLE_G: GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA, GL_ZERO, GL_ONE GL_TEXTURE_SWIZZLE_B: GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA, GL_ZERO, GL_ONE GL_TEXTURE_SWIZZLE_A: GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA, GL_ZERO, GL_ONE GL_TEXTURE_SWIZZLE_RGBA: GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA, GL_ZERO, GL_ONE GL_TEXTURE_WRAP_S: GL_CLAMP_TO_EDGE, GL_CLAMP_TO_BORDER, GL_MIRRORED_REPEAT, GL_REPEAT, GL_MIRROR_CLAMP_TO_EDGE GL_TEXTURE_WRAP_T: GL_CLAMP_TO_EDGE, GL_CLAMP_TO_BORDER, GL_MIRRORED_REPEAT, GL_REPEAT, GL_MIRROR_CLAMP_TO_EDGE GL_TEXTURE_WRAP_R: GL_CLAMP_TO_EDGE, GL_CLAMP_TO_BORDER, GL_MIRRORED_REPEAT, GL_REPEAT, GL_MIRROR_CLAMP_TO_EDGE ) glTexEnvf( GL_TEXTURE_ENV, GL_POINT_SPRITE_OES , GL_TEXTURE_ENV_MODE, GL_COMBINE_RGB, GL_COMBINE_ALPHA, GL_SRC0_RGB, GL_SRC1_RGB, GL_SRC2_RGB, GL_SRC0_ALPHA, GL_SRC1_ALPHA, GL_SRC2_ALPHA, GL_OPERAND0_RGB, GL_OPERAND1_RGB, GL_OPERAND2_RGB, GL_OPERAND0_ALPHA, GL_OPERAND1_ALPHA, GL_OPERAND2_ALPHA, GL_RGB_SCALE, GL_ALPHA_SCALE, GL_COORD_REPLACE_OES , GL_ADD, GL_ADD_SIGNED, GL_DOT3_RGB, GL_DOT3_RGBA, GL_INTERPOLATE, GL_MODULATE, GL_DECAL, GL_BLEND, GL_REPLACE, GL_SUBTRACT, GL_COMBINE, GL_TEXTURE, GL_CONSTANT, GL_PRIMARY_COLOR, GL_PREVIOUS, GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, (a single boolean value for the point sprite texture coordinate replacement, or 1.0, 2.0, or 4.0 when specifying the GL_RGB_SCALE or GL_ALPHA_SCALE) ) ''' LC0,LC1=[0,0,0,0],[0,0,0,0] #Remember last used colors (starts at transparent black) for Primitive,Facepoints in MeshPrimitives: __GL.glBegin(__UMCGLPRIMITIVES[Primitive]) for V,N,(C0,C1),(U0,U1,U2,U3,U4,U5,U6,U7) in Facepoints: try: if U0!='': __GL.glMultiTexCoord2f(__GL.GL_TEXTURE0,MeshUVs[0][U0][0],MeshUVs[0][U0][1]) #if U1!='': glMultiTexCoord2f(GL_TEXTURE1,Fl(UVs[1][U1][0]),Fl(UVs[1][U1][1])) #if U2!='': glMultiTexCoord2f(GL_TEXTURE2,Fl(UVs[2][U2][0]),Fl(UVs[2][U2][1])) #if U3!='': glMultiTexCoord2f(GL_TEXTURE3,Fl(UVs[3][U3][0]),Fl(UVs[3][U3][1])) #if U4!='': glMultiTexCoord2f(GL_TEXTURE4,Fl(UVs[4][U4][0]),Fl(UVs[4][U4][1])) #if U5!='': glMultiTexCoord2f(GL_TEXTURE5,Fl(UVs[5][U5][0]),Fl(UVs[5][U5][1])) #if U6!='': glMultiTexCoord2f(GL_TEXTURE6,Fl(UVs[6][U6][0]),Fl(UVs[6][U6][1])) #if U7!='': glMultiTexCoord2f(GL_TEXTURE7,Fl(UVs[7][U7][0]),Fl(UVs[7][U7][1])) #max texture is 31 except: #TODO: note UV display error pass if C0!='': #IRAGBA format C0L=len(MeshColors[0][C0]) C0R,C0G,C0B,C0A=[__if2f(MeshColors[0][C0][0]), __if2f(MeshColors[0][C0][1]) if C0L>2 else __if2f(MeshColors[0][C0][0]), __if2f(MeshColors[0][C0][2]) if C0L>2 else __if2f(MeshColors[0][C0][0]), __if2f(MeshColors[0][C0][3]) if C0L==4 else (__if2f(MeshColors[0][C0][1]) if C0L==2 else 1.0)] __GL.glColor4f((MAR+MDR+C0R)/3,(MAG+MDG+C0G)/3,(MAB+MDB+C0B)/3,(MAA+MDA+C0A)/3) if C1!='': #IRAGBA format C1L=len(MeshColors[1][C1]) C1R,C1G,C1B,C1A=[__if2f(MeshColors[1][C1][0]), __if2f(MeshColors[1][C1][1]) if C1L>2 else __if2f(MeshColors[1][C1][0]), __if2f(MeshColors[1][C1][2]) if C1L>2 else __if2f(MeshColors[1][C1][0]), __if2f(MeshColors[1][C1][3]) if C1L==4 else (__if2f(MeshColors[1][C1][1]) if C1L==2 else 1.0)] __GL.glSecondaryColor3f(C1R,C1G,C1B) #Alpha is supported but not registered here (glSecondaryColor4f is not a registered function) UpdateMat=0 if LC0!=[C0R,C0G,C0B,C0A]: UpdateMat=1; LC0=[C0R,C0G,C0B,C0A] #if LC1!=[C1R,C1G,C1B,C1A]: UpdateMat=1; LC1=[C1R,C1G,C1B,C1A] if UpdateMat: __GL.glMaterialfv(__GL.GL_FRONT_AND_BACK, __GL.GL_AMBIENT, [(MAR+C0R)/2,(MAG+C0G)/2,(MAB+C0B)/2,(MAA+C0A)/2]) __GL.glMaterialfv(__GL.GL_FRONT_AND_BACK, __GL.GL_DIFFUSE, [(MDR+C0R)/2,(MDG+C0G)/2,(MDB+C0B)/2,(MDA+C0A)/2]) __GL.glMaterialfv(__GL.GL_FRONT_AND_BACK, __GL.GL_SPECULAR, [(MSR+C0R)/2,(MSG+C0G)/2,(MSB+C0B)/2,(MSA+C0A)/2]) #__GL.glMaterialfv(__GL.GL_FRONT_AND_BACK, __GL.GL_SPECULAR, [0,0,0,1]) __GL.glMaterialfv(__GL.GL_FRONT_AND_BACK, __GL.GL_EMISSION, [MER,MEG,MEB,MEA]) __GL.glMaterialf(__GL.GL_FRONT_AND_BACK, __GL.GL_SHININESS, MSV) if N!='': __GL.glNormal3f(MeshNormals[N][0],MeshNormals[N][1],MeshNormals[N][2]) VL=len(MeshVerts[V]) VX,VY,VZ=MeshVerts[V]+([0.0] if VL==2 else []) __GL.glVertex3f(VX,VY,VZ) __GL.glEnd() __GL.glEndList() def __N(): global Libs,__UMCGLPRIMITIVES,__NORMAL_DATA __NORMAL_DATA = __GL.glGenLists(1) __GL.glNewList(__NORMAL_DATA, __GL.GL_COMPILE) __GL.glLineWidth(1.0) __GL.glColor3f(0,1,1) for Name,Objects in Libs[2]: for ID in Objects: ObjectName,Viewport,LRS,Sub_Data,Parent_ID=Libs[3][ID] SDType,SDName,SDData1,SDData2=Sub_Data if SDType=="_Mesh": Verts,Normals,Colors,UVs,Weights,Primitives=SDData2 for Primitive,Facepoints in Primitives: __GL.glBegin(__GL.GL_LINES) for V,N,Cs,Us in Facepoints: if N!='': NX,NY,NZ=Normals[N][0],Normals[N][1],Normals[N][2] VL=len(Verts[V]) VX,VY,VZ=Verts[V]+([0.0] if VL==2 else []) __GL.glVertex3f(VX,VY,VZ) __GL.glVertex3f(VX+NX,VY+NY,VZ+NZ) __GL.glEnd() __GL.glEndList() def __B(): global Libs,__BONE_DATA __BONE_DATA = __GL.glGenLists(1) glNewList(__BONE_DATA, GL_COMPILE) for Name,Objects in Libs[2]: for ID in Objects: ObjectName,Viewport,LRS,Sub_Data,Parent_ID=Libs[3][ID] SDType,SDName,SDData1,SDData2=Sub_Data if SDType=="_Rig": __GL.glLineWidth(3.5) for bone in SDData2: PLRS,CLRS = (SDData2[bone[4]][2] if type(bone[4])==int else [0,0,0,0,0,0,1,1,1]),bone[2] __GL.glBegin(GL_LINES) __GL.glColor3f(1,1,1) __GL.glVertex3f((PLRS[0]*PLRS[6]),(PLRS[1]*PLRS[7]),(PLRS[2]*PLRS[8])) __GL.glVertex3f((CLRS[0]*CLRS[6]),(CLRS[1]*CLRS[7]),(CLRS[2]*CLRS[8])) __GL.glEnd() __GL.glEndList() def __Draw_Scene(): global TOGGLE_FULLSCREEN,TOGGLE_LIGHTING,TOGGLE_3D,TOGGLE_WIREFRAME,TOGGLE_BONES,TOGGLE_ORTHO,TOGGLE_NORMALS global __viewMatrix global __TOP_GRID,__SIDE_GRID,__FRONT_GRID,__QUAD_FLOOR,__LINE_FLOOR,__MODEL_DATA,__NORMAL_DATA,__BONE_DATA __GL.glMultMatrixf(__viewMatrix._getMtx()) __GL.glEnable(__GL.GL_DEPTH_TEST) __GL.glDisable(__GL.GL_LIGHTING) #disable for the grid if TOGGLE_GRID<4: #global __TOP_GRID,__SIDE_GRID,__FRONT_GRID,__QUAD_FLOOR __GL.glCallList([__TOP_GRID,__SIDE_GRID,__FRONT_GRID,__QUAD_FLOOR][TOGGLE_GRID]) if TOGGLE_LIGHTING: __GL.glEnable(__GL.GL_LIGHTING) __GL.glEnable(__GL.GL_TEXTURE_2D) __GL.glCallList(__MODEL_DATA) __GL.glDisable(__GL.GL_TEXTURE_2D) if TOGGLE_LIGHTING: __GL.glDisable(__GL.GL_LIGHTING) #disable for the grid and bones if TOGGLE_NORMALS: __GL.glCallList(__NORMAL_DATA) if TOGGLE_BONES: if TOGGLE_BONES==2: __GL.glClear( __GL.GL_DEPTH_BUFFER_BIT ) #overlay the bones (X-Ray) __GL.glCallList(__BONE_DATA) for Name,Objects in Libs[2]: #de-scaled bone joints for ID in Objects: ObjectName,Viewport,LRS,Sub_Data,Parent_ID=Libs[3][ID] SDType,SDName,SDData1,SDData2=Sub_Data if SDType=="_Rig": for bone in SDData2: PLRS,CLRS = (SDData2[bone[4]][2] if type(bone[4])==int else [0,0,0,0,0,0,1,1,1]),bone[2] __GL.glTranslate((CLRS[0]*CLRS[6]),(CLRS[1]*CLRS[7]),(CLRS[2]*CLRS[8])) #glutSolidSphere(0.03/__viewMatrix._scale, 25, 25) __GL.glTranslate(-(CLRS[0]*CLRS[6]),-(CLRS[1]*CLRS[7]),-(CLRS[2]*CLRS[8])) __GL.glDisable(__GL.GL_DEPTH_TEST) pass #___________________________________________________________________________________________ def __G(D): #Grid __GL.glLineWidth(1.0) GS=60; i0,i1 = (D+1 if D<2 else 0),(D-1 if D>0 else 2) C1,C2,A1,A2,nA1,nA2=[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0] C1[D],C2[i0]=1,1 A1[D],A2[i0]=GS,GS; nA1[D],nA2[i0]= -GS,-GS S1,iS1=A1,A1;S2,iS2=A2,A2; nS1,niS1=nA1,nA1;nS2,niS2=nA2,nA2 __GL.glBegin(__GL.GL_LINES) __GL.glColor3fv(C1);__GL.glVertex3f(A1[0],A1[1],A1[2]);__GL.glVertex3f(nA1[0],nA1[1],nA1[2]) __GL.glColor3fv(C2);__GL.glVertex3f(A2[0],A2[1],A2[2]);__GL.glVertex3f(nA2[0],nA2[1],nA2[2]) __GL.glColor3f(0.5,0.5,0.5) s=0 while s < GS: s+=10; S1[i0],nS1[i0],S2[D],nS2[D]=s,s,s,s __GL.glVertex3f(S1[0],S1[1],S1[2]);__GL.glVertex3f(nS1[0],nS1[1],nS1[2]) __GL.glVertex3f(S2[0],S2[1],S2[2]);__GL.glVertex3f(nS2[0],nS2[1],nS2[2]) iS1[i0],niS1[i0],iS2[D],niS2[D]=-s,-s,-s,-s __GL.glVertex3f(iS1[0],iS1[1],iS1[2]);__GL.glVertex3f(niS1[0],niS1[1],niS1[2]) __GL.glVertex3f(iS2[0],iS2[1],iS2[2]);__GL.glVertex3f(niS2[0],niS2[1],niS2[2]) __GL.glEnd() def __quad(p1,p2): __GL.glVertex3f(p1+2.5,0,p2+2.5); __GL.glVertex3f(p1+2.5,0,p2-2.5) __GL.glVertex3f(p1-2.5,0,p2-2.5); __GL.glVertex3f(p1-2.5,0,p2+2.5) def __F(D): #Floor __GL.glLineWidth(1.0) FS=40; clr=0.3125; p1=0 while p1 < FS: clr=(0.3125 if clr==0.5 else 0.5); p2=0 while p2 < FS: __GL.glColor3f(clr,clr,clr) if D: #draw lines so you can actually see the floor __GL.glBegin(__GL.GL_LINE_LOOP); __quad(p1,p2); __GL.glEnd() __GL.glBegin(__GL.GL_LINE_LOOP); __quad(p1,-p2); __GL.glEnd() __GL.glBegin(__GL.GL_LINE_LOOP); __quad(-p1,-p2); __GL.glEnd() __GL.glBegin(__GL.GL_LINE_LOOP); __quad(-p1,p2); __GL.glEnd() #TODO: this draws lines for every quad instead of just the outside quads #^a performance killer >_> else: __GL.glBegin(__GL.GL_QUADS) __quad(p1,p2); __quad(p1,-p2) __quad(-p1,p2); __quad(-p1,-p2) __GL.glEnd() p2+=5; clr=(0.3125 if clr==0.5 else 0.5) p1+=5 def __SDLVResize(W,H, VMODE): #A limitation of SDL (the GL context also needs to be reset with the screen) __pyg.display.set_mode((int(W),int(H)), VMODE) #DspInf = __pyg.display.Info() #UI display lists: global __TOP_GRID,__SIDE_GRID,__FRONT_GRID,__QUAD_FLOOR,__LINE_FLOOR __FRONT_GRID = __GL.glGenLists(1); __GL.glNewList(__FRONT_GRID, __GL.GL_COMPILE); __G(2); __GL.glEndList() __SIDE_GRID = __GL.glGenLists(1); __GL.glNewList(__SIDE_GRID, __GL.GL_COMPILE); __G(1); __GL.glEndList() __TOP_GRID = __GL.glGenLists(1); __GL.glNewList(__TOP_GRID, __GL.GL_COMPILE); __G(0); __GL.glEndList() __QUAD_FLOOR = __GL.glGenLists(1); __GL.glNewList(__QUAD_FLOOR, __GL.GL_COMPILE); __F(0); __GL.glEndList() __LINE_FLOOR = __GL.glGenLists(1); __GL.glNewList(__LINE_FLOOR, __GL.GL_COMPILE); __F(1); __GL.glEndList() __GL.glClearColor(0.13, 0.13, 0.13, 1.0) __GL.glClearDepth(1.0) #TODO: need to manage these more efficiently: __GL.glEnable(__GL.GL_DEPTH_TEST) __GL.glDepthFunc(__GL.GL_LEQUAL) __GL.glEnable(__GL.GL_LIGHTING) __GL.glEnable(__GL.GL_LIGHT0) __GL.glEnable(__GL.GL_NORMALIZE) #scale normals when model is scaled __GL.glDisable(__GL.GL_BLEND) #disabled for models __GL.glBlendFunc(__GL.GL_SRC_ALPHA, __GL.GL_ONE_MINUS_SRC_ALPHA) __GL.glShadeModel(__GL.GL_SMOOTH) __M(); __N(); __B() __GUI.__ResizeGUI(W,H) def Init(): import sys global TOGGLE_FULLSCREEN,TOGGLE_LIGHTING,TOGGLE_GRID,TOGGLE_WIREFRAME,TOGGLE_BONES,TOGGLE_3D,TOGGLE_ORTHO global width,height global W,H; LW,LH=W,H #restored screen size (coming from full-screen) VIDEOMODE = OPENGL|DOUBLEBUF|RESIZABLE #VIDEOMODE&=~RESIZABLE __pyg.display.init() icon = __pyg.Surface((1,1)); icon.set_alpha(255) __pyg.display.set_icon(icon) __pyg.display.set_caption("Universal Model Converter v3.0a (dev4.5)") __SDLVResize(width,height, VIDEOMODE) __GUI.__initGUI() '''later''' #__pyg.joystick.init() #joy = [__pyg.joystick.Joystick(j) for j in range(__pyg.joystick.get_count())] #for j in joy: j.init() __lastRot = __AB.Matrix3fT() #last updated rotation (ArcBall view rotation) O = 0.025 # eye translation offset EYE=None #3D L or R EYE (for Shutter method) MODS=0 #Modifier keys (global use) [ Alt(4)[0b100] | Ctrl(2)[0b10] | Shift(1)[0b1] ] #global __MODEL_DATA,__NORMAL_DATA,__BONE_DATA while True: ''' line=0 for axis in range(GCNJS.get_numaxes()): #sys.stdout.write("axis%i: %s\n"%(axis,str(GCNJS.get_axis(axis)))) GCNJS.get_axis(axis) line+=1 for hat in range(GCNJS.get_numhats()): #sys.stdout.write("hat%i: %s\n"%(hat,str(GCNJS.get_hat(hat)))) GCNJS.get_hat(hat) line+=1 for button in range(GCNJS.get_numbuttons()): #sys.stdout.write("button%i: %s\n"%(button,str(GCNJS.get_button(button)))) GCNJS.get_button(button) line+=1 #sys.stdout.write('%s'%('\r'*line)) ''' for i,e in enumerate(__pyg.event.get()): if e.type == QUIT: __pyg.display.quit(); return None #VIEWER.init() >>> None if e.type == ACTIVEEVENT: pass #e.gain; e.state if e.type == KEYDOWN: #e.key; e.mod __GUI.__KeyPress(e.key) if e.key==K_RSHIFT or e.key==K_LSHIFT: MODS|=1 if e.key==K_RCTRL or e.key==K_LCTRL: MODS|=2 if e.key==K_RALT or e.key==K_LALT: MODS|=4 if e.key not in [K_RSHIFT,K_LSHIFT,K_RCTRL,K_LCTRL,K_RALT,K_LALT]: TOGGLE_GRID=(2 if TOGGLE_GRID<3 else TOGGLE_GRID) #don't let MODS affect the grid if e.key==K_KP5: TOGGLE_ORTHO = False if TOGGLE_ORTHO else True if e.key==K_KP9: #reset the view if MODS==0: __viewMatrix.mtxrotate(__AB.Matrix3fT()) #rotation __viewMatrix.rotate(10.0,350.0,0.0) elif MODS&1: __viewMatrix.X=0.0;__viewMatrix.Y=0.0;__viewMatrix.Z=0.0 #translation elif MODS&2: __viewMatrix._scale=0.1 #scale elif MODS&4: __viewMatrix.reset() #everything if e.key==K_KP8: #rotate/translate U if MODS&1: __viewMatrix.translate(0.0,-0.25,0.0) else: __viewMatrix.rotate(5.0,0.0,0.0) if e.key==K_KP2: #rotate/translate D if MODS&1: __viewMatrix.translate(0.0,0.25,0.0) else: __viewMatrix.rotate(-5.0,0.0,0.0) if e.key==K_KP4: #rotate/translate L if MODS&1: __viewMatrix.translate(0.25,0.0,0.0) else: __viewMatrix.rotate(0.0,5.0,0.0) if e.key==K_KP6: #rotate/translate R if MODS&1: __viewMatrix.translate(-0.25,0.0,0.0) else: __viewMatrix.rotate(0.0,-5.0,0.0) #//--// kept as an added option if e.key==K_KP_PLUS: __viewMatrix.scale(1.1) if e.key==K_KP_MINUS: __viewMatrix.scale(1/1.1) #//--// if e.key==K_KP1: #front view TOGGLE_GRID=(0 if TOGGLE_GRID<3 else TOGGLE_GRID) __viewMatrix.mtxrotate(__AB.Matrix3fT()) #reset the rotation using a minor bug if MODS&2: __viewMatrix.rotate(0.0,180.0,0.0) #back View if e.key==K_KP3: TOGGLE_GRID=(1 if TOGGLE_GRID<3 else TOGGLE_GRID) __viewMatrix.mtxrotate(__AB.Matrix3fT()) #reset the rotation if MODS&2: __viewMatrix.rotate(0.0,90.0,0.0) #right-side View else: __viewMatrix.rotate(0.0,-90.0,0.0) #left-side view if e.key==K_KP7: TOGGLE_GRID=(2 if TOGGLE_GRID<3 else TOGGLE_GRID) __viewMatrix.mtxrotate(__AB.Matrix3fT()) #reset the rotation if MODS&2: __viewMatrix.rotate(-90.0,0.0,0.0) #bottom View else: __viewMatrix.rotate(90.0,0.0,0.0) #top view if e.key==K_ESCAPE: if TOGGLE_FULLSCREEN: TOGGLE_FULLSCREEN=0 VIDEOMODE&=~FULLSCREEN VIDEOMODE|=RESIZABLE W,H = LW,LH else: TOGGLE_FULLSCREEN=1 VIDEOMODE&=~RESIZABLE VIDEOMODE|=FULLSCREEN LW,LH=W,H; W,H = 1280,1024 __SDLVResize(W,H, VIDEOMODE) __abt.setBounds(W,H) ##### Import/Export if e.key==K_i: if MODS&2: ##import model import COMMON typenames,modules,modnames,ihandlers = [],[],[],[]; iftypes,isupport = [],[] for M,D,I in COMMON._Scripts[0][0]: if D[1] != ('',['']): #has model info iftypes+=[(D[1][0],tuple(["*.%s"%T for T in D[1][1]]))] for T in D[1][1]: try: isupport.index("*.%s"%T) except: isupport+=["*.%s"%T] modnames+=[D[1][0]] typenames+=[T] modules+=[M] ihandlers+=[I] #print ihandlers #----- Tkinter dialog (will be replaced) _in=askopenfilename(title='Import Model', filetypes=[('Supported', " ".join(isupport))]+iftypes) #----- if _in=='': pass #action cancelled else: COMMON.__functions=[0,0,0,0] #prevent unwanted initialization #this block will change once I use my own dialog #Tkinter doesn't return the filter ID #----- it = _in.split('.')[-1] if typenames.count(it)>1: print '\nThis filetype is used by multiple scripts:\n' scr = [] for idx,ft in enumerate(typenames): if ft==it: scr+=[[modnames[idx],modules[idx],ihandlers[idx]]] for I,NM in enumerate(scr): print ' %i - %s'%(I,NM[0]) print sid=input('Please enter the script ID here: ') i=__import__(scr[sid][1]) for iM,iD in COMMON._Scripts[2][0]: if iD[1] != ('',['']): #has image info if iD[1][0] in scr[sid][2]: for iift in iD[1][1]: COMMON._ImgScripts[iift] = iM #save memory, and don't import here as it's already imported else: idx = typenames.index(it) i=__import__(modules[idx]) for iM,iD in COMMON._Scripts[2][0]: if iD[1] != ('',['']): #has image info if iD[1][0] in ihandlers[idx]: for iift in iD[1][1]: COMMON._ImgScripts[iift] = iM COMMON.__ReloadScripts() #check for valid changes to the scripts #----- global Libs; __Libs=Libs #remember last session in case of a script error try: #can we get our hands on the file, and does the script work? COMMON.__d[COMMON.__c] = '' #hack COMMON.ImportFile(_in,1) #set the file data Libs=[[],[],[["Def_Scene",[]]],[],[],[],[],[]] #reset the data for importing __FORMAT._Reset() print 'Converting from import format...' __LOG('-- importing %s --\n'%_in.split('/')[-1]) i.ImportModel(it,None) print 'Verifying data...' #export UMC session data l=open('session.ses','w') l.write(str([1,Libs])) l.close() __M() #model Display __N() __B() print 'Updating Viewer\n' __pyg.display.set_caption("Universal Model Converter v3.0a (dev4.5) - %s" % _in.split('/')[-1]) #glutSetWindowTitle("Universal Model Converter v3.0a (dev5) - %s" % _in.split('/')[-1]) COMMON.__ClearFiles() #clear the file data to be used for writing except: Libs=__Libs print "Error! Check 'session-info.log' for more details.\n" import sys,traceback typ,val,tb=sys.exc_info()#;tb=traceback.extract_tb(i[2])[0] traceback.print_exception( typ,val,tb#, #limit=2, #file=sys.stdout ) print __Libs=[] #save memory usage COMMON._ImgScripts = {} #reset __WLOG(0) #write log COMMON.__CleanScripts() #remove pyc files if e.key==K_e: if MODS&2: #export model COMMON.__ClearFiles() #clear the file data again... just in case etypenames,emodules,emodnames,ehandlers = [],[],[],[]; eftypes = [] for M,D,I in COMMON._Scripts[0][1]: if D[1] != ('',['']): #has model info eftypes+=[(D[1][0],tuple(["*.%s"%T for T in D[1][1]]))] for T in D[1][1]: emodnames+=[D[1][0]] etypenames+=[T] emodules+=[M] ehandlers+=[I] COMMON.__ReloadScripts() #check for valid changes to the scripts #Tkinter dialog (will be replaced) #----- _en=asksaveasfilename(title='Export Model', filetypes=eftypes, defaultextension='.ses') #----- if _en=='': pass else: COMMON.__functions=[0,0,0,0] #prevent unwanted initialization #this block will change once I use my own dialog #Tkinter doesn't return the filter ID #----- et = _en.split('.')[-1] if etypenames.count(et)>1: print '\nThis filetype is used by multiple scripts:\n' scr = [] for idx,ft in enumerate(etypenames): if ft==et: scr+=[[emodnames[idx],emodules[idx]]] for I,NM in enumerate(scr): print ' %i - %s'%(I,NM[0]) print sid=input('Please enter the script ID here: ') em=__import__(scr[sid][1]) else: em=__import__(emodules[etypenames.index(et)]) #----- try: COMMON.ExportFile(_en) #add the file to the data space print 'converting to export format...' em.ExportModel(et,None) COMMON.__WriteFiles() print 'Done!' except: print "Error! Check 'session-info.log' for more details.\n" import sys,traceback typ,val,tb=sys.exc_info()#;tb=traceback.extract_tb(i[2])[0] print traceback.print_exception( typ,val,tb#, #limit=2, #file=sys.stdout ) __WLOG(0) #write log COMMON.__CleanScripts() #remove pyc files ##### if e.type == KEYUP: #e.key; e.mod __GUI.__KeyRelease(e.key) if e.key==K_RSHIFT or e.key==K_LSHIFT: MODS&=6 if e.key==K_RCTRL or e.key==K_LCTRL: MODS&=5 if e.key==K_RALT or e.key==K_LALT: MODS&=3 if e.type == MOUSEBUTTONDOWN: #e.pos; e.button x,y=e.pos __GUI.__Click(e.button,x,y) if e.button==2: __lastRot=__viewMatrix.RotMtx __abt.click(__AB.Point2fT(x,y)) else: __lastRot=__viewMatrix.RotMtx if e.button==4: if MODS==0: __viewMatrix.scale(1.1) elif MODS&1: __viewMatrix.translate(0.0,0.25,0.0) #translate Y elif MODS&2: __viewMatrix.translate(0.25,0.0,0.0) #translate X elif e.button==5: if MODS==0: __viewMatrix.scale(1/1.1) elif MODS&1: __viewMatrix.translate(0.0,-0.25,0.0) #translate Y elif MODS&2: __viewMatrix.translate(-0.25,0.0,0.0) #translate X if e.type == MOUSEBUTTONUP: #e.pos; e.button x,y=e.pos __GUI.__Release(e.button,x,y) if e.button==2: __lastRot=__viewMatrix.RotMtx if e.type == MOUSEMOTION: #e.pos; e.rel; e.buttons x,y = e.pos; rx,ry = e.rel __GUI.__Motion(e.buttons,x,y,rx,ry) if e.buttons[1]: #MMB view rotation (like blender24) if MODS&1: s = __viewMatrix._scale tx = ((1./W)*rx)/s ty = ((1./H)*-ry)/s __viewMatrix.translate(tx,ty,0.0) elif MODS&2: s = ry __viewMatrix.scale(s) else: __viewMatrix.mtxrotate( __AB.Matrix3fMulMatrix3f( __lastRot, #get our previous view rot matrix __AB.Matrix3fSetRotationFromQuat4f(__abt.drag(__AB.Point2fT(x,y))) #get a rot matrix from the mouse position ) #multiply the matrices ) #update the view matrix with the new rotation if TOGGLE_GRID<3 and TOGGLE_GRID!=2: TOGGLE_GRID=2 if e.type == JOYAXISMOTION: #e.joy; e.axis; e.value pass #print 'Joy:',e.joy, ', Axis:',e.axis, ', Value:',e.value if e.type == JOYBALLMOTION: pass #e.joy; e.ball; e.rel if e.type == JOYHATMOTION: #e.joy; e.hat; e.value pass #print 'Joy:',e.joy, ', Hat:',e.hat, ', Value:',e.value if e.type == JOYBUTTONDOWN: #e.joy; e.button pass #print 'Joy:',e.joy, ', Button:',e.button if e.type == JOYBUTTONUP: pass #e.joy; e.button if e.type == VIDEORESIZE: #e.size; e.w; e.h _w,_h = e.size if _w+_h>0 and _h>0: W,H=_w,_h __SDLVResize(W,H, VIDEOMODE) __abt.setBounds(W,H) if e.type == VIDEOEXPOSE: pass if e.type == USEREVENT: pass #e.code #Display: __GL.glViewport(0, 0, int(W), int(H)) ### __GL.glMatrixMode(__GL.GL_PROJECTION) __GL.glLoadIdentity() P=float(W)/float(H) if TOGGLE_ORTHO: __GL.glOrtho(-2*P, 2*P, -2, 2, -100, 100) else: __GLU.gluPerspective(43.6025, P, 1, 100.0); __GLU.gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) #gluLookAt( eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz) #glOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near, GLdouble far) #glFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near, GLdouble far) #gluPerspective(GLdouble fovy, GLdouble aspect, GLdouble near, GLdouble far) ### __GL.glMatrixMode(__GL.GL_MODELVIEW) __GL.glLoadIdentity() __GL.glClear(__GL.GL_COLOR_BUFFER_BIT|__GL.GL_DEPTH_BUFFER_BIT) __GL.glPushMatrix() __GL.glLightfv(__GL.GL_LIGHT0, __GL.GL_POSITION, ( 1.0, 1.0, 3.0, 0.0 )) __GL.glPolygonMode(__GL.GL_FRONT_AND_BACK,(__GL.GL_LINE if TOGGLE_WIREFRAME else __GL.GL_FILL)) if TOGGLE_3D==1: #Analglyph __GL.glDrawBuffer( __GL.GL_BACK_LEFT ) #not really sure why this is needed, #but the code doesn't work if removed... #L Eye (2 colors) if TOGGLE_3D_MODE[0]==0: __GL.glColorMask( 1,0,0,1 ) elif TOGGLE_3D_MODE[0]==1: __GL.glColorMask( 0,1,0,1 ) elif TOGGLE_3D_MODE[0]==2: __GL.glColorMask( 0,0,1,1 ) __GL.glClear( __GL.GL_COLOR_BUFFER_BIT | __GL.GL_DEPTH_BUFFER_BIT ) __GL.glLoadIdentity(); __GL.glTranslate(O,0.0,0.0) __Draw_Scene() #R Eye (1 color) if TOGGLE_3D_MODE[0]==0: __GL.glColorMask( 0,1,1,1 ) #doesn't overlay if TOGGLE_3D_MODE[0]==1: __GL.glColorMask( 1,0,1,1 ) if TOGGLE_3D_MODE[0]==2: __GL.glColorMask( 1,1,0,1 ) __GL.glClear( __GL.GL_DEPTH_BUFFER_BIT ) __GL.glLoadIdentity(); __GL.glTranslate(-O*2,0.0,0.0) __Draw_Scene() __GL.glColorMask( 1,1,1,1 ) #restore the color mask for later drawing elif TOGGLE_3D==2: #Shutter (need a better method than simply rotating between frames) #does not require quad-buffered hardware. (I might add error-detection-support for this later) #... if your machine supports this, it should greatly improve visual performance quality ;) EYE=(-O if EYE==O else O) __viewMatrix.translate(EYE,0.0,0.0) __Draw_Scene() else: __Draw_Scene() #no 3D display __GL.glPopMatrix() __GL.glPolygonMode(__GL.GL_FRONT_AND_BACK,(__GL.GL_FILL)) __GUI.__DrawGUI(W,H,__viewMatrix.getaxismtx()) __pyg.display.flip() #Init()
{ "repo_name": "Universal-Model-Converter/UMC3.0a", "path": "data/VIEWER.py", "copies": "1", "size": "55702", "license": "mit", "hash": 5523323525696215000, "line_mean": 50.1976102941, "line_max": 211, "alpha_frac": 0.486391871, "autogenerated": false, "ratio": 2.848624322389281, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.38350161933892807, "avg_score": null, "num_lines": null }
#1 #v 0.001 ''' description: UMC's GUI, instead of using the GL Feedback Buffer like any normal GUI, uses it's own interface based on hitdefs. how it works is it fills 2 buffers with data: - Widgets: holds the widget data (info), event states, and hitdef - layer: holds a complex arrangement of polygon layers the Widgets buffer is accessed only by the input functions and the widget functions. - the input functions trigger event states based on if the mouse is over an active hitdef - the widget functions simply modify the state info if a particular widget. (based on the widget name) they also modify the coordinates of the polygons, and draw or remove polygons in the layer buffer the layer buffer is filled by the widget functions only once (it is never cleared) it is accessed after widget managment. the buffer has 3 internal layers: - the stack layer is an arrangement of polygons drawn from *max_size* (FG) to 0 (BG). there is no mixed alpha between the FGs and BGs - the overlay layer is drawn over the stack layer this has the same structure as the stack layer, however all alphas are mixed - the font layer is always the same length as the overlay layer the internal layers here get sandwiched between the overlay layers the use of these buffers is to build a smart GUI that manages itself to deliver the best perfomance and change what's needed only when needed to. (this cuts out 98% of the math needed to position everything) the reason I decided to build this instead of using GL's buffer to manage this is because in order to use the feedback buffer, you'd have to calculate the positions once when drawing the data, and then recalculate them for the feedback mode to verify a hit. (eg: the hitdefs) with this, the positions only need to be calculated once. once created, the data isn't ment to be removed, however, it can be disabled until needed again. (disabling the data will cause the display parser to simply skip over the data) issues: while this method has worked, it's not perfected, and due to the large amount of widgets created for UMC's GUI, it does cause a bit of lag. (30 FPS at least) one of these problems would be that the display parser draws the data in immediate mode. (the vertex data and primitives are drawn individually and parsed as is) a better solution would be either: - use a single display list and recompile the data only when modified - use a display list for each widget (and sub-widgets) and parse/draw only the needed display lists I personally would go for the first option as this would allow for better performance when viewing the scene. ''' import COMMON #file vars and functions for import/export processing import VIEWER #mainly for the toggles from VIEWER import __GL,__GLU,__pyg from array import array as __arr class __Widget: class _event: #widget events def __init__(self): self.gainFocus=False #True for the first frame the cursor enters the hitspace self.loseFocus=False #True for the first frame the cursor leaves the hitspace self.hasFocus=False #True if the cursor is in the hitspace self.clickL=False #True if the L mouse button was clicked self.clickM=False #True if the M mouse button was clicked self.clickR=False #True if the R mouse button was clicked self.holdL=False #True if the L mouse button is held self.holdM=False #True if the M mouse button is held self.holdR=False #True if the R mouse button is held self.releaseL=False #True if the L mouse button was released self.releaseM=False #True if the M mouse button was released self.releaseR=False #True if the R mouse button was released self.scrollU=False #True if scrolling up self.scrollD=False #True if scrolling down self.keyPress=False #True if a key was pressed self.keyHold=False #True if a key is being held self.keyRelease=False#True if a key was released class _hitdef: #Widget mouse-hit area #the event handlers manage the widgets by their hit-defs. #if the mouse does something within the widget's hit-def area, the widget is updated def __init__(self): self.enabled=True #allow hitdef testing self.x=0.0; self.y=0.0 self.X=0.0; self.Y=0.0 def __init__(self): self.info=None #state info filled and used by the widget's creation function self.event=self._event() #Widget.event.*wevent* self.hitdef=self._hitdef() self.motion=False #allow repositioning self.allowKeys=False #triggered by a widget (allows handling by the GUI sub-system) self.key=None #the keys in which was pressed/released class __Layer: class _PrimitiveCollector: class _Primitive: def __init__(self,isTri,r,g,b,a,v1,v2,v3,v4=None): self.r,self.g,self.b,self.a=r,g,b,a self.v1,self.v2,self.v3,self.v4=v1,v2,v3,v4 self.isTri=isTri def Position(self,v1,v2,v3,v4=None): if (v1,v2,v3,v4)!=(self.v1,self.v2,self.v3,self.v4): self.v1,self.v2,self.v3,self.v4=v1,v2,v3,v4; return True else: return False def Color(self,r,g,b,a): fcm=1./255; r,g,b,a=r*fcm,g*fcm,b*fcm,a*fcm if (self.r,self.g,self.b,self.a)!=(r,g,b,a): self.r,self.g,self.b,self.a=r,g,b,a; return True else: return False def __init__(self): self.primitives={} def HasPrimitive(self,Name): return Name in self.primitives def AddTri(self,Name,v1,v2,v3,color=(0,0,0,0)): fcm=1./255; r,g,b,a=color self.primitives[Name]=self._Primitive(True,r*fcm,g*fcm,b*fcm,a*fcm,v1,v2,v3) def AddQuad(self,Name,v1,v2,v3,v4,color=(0,0,0,0)): fcm=1./255; r,g,b,a=color self.primitives[Name]=self._Primitive(False,r*fcm,g*fcm,b*fcm,a*fcm,v1,v2,v3,v4) def RemovePrimitive(self,Name): self.primitives.pop(Name) class _FontCollector: import GUI class _String(GUI): #NOTE: the GUI part is new #self.pw,self.ph=pw,ph def __init__(self,image,text,x,y,X,Y,w,h): self.image=None #an alpha mask texture self.x,self.y=0,0 self.w,self.h=w,h #local usage: self.rect=[] Position(self,x,y,X,Y) def Position(self,x,y,X,Y): if (x,y,X,Y)!=self.last: pw=self.pw ph=self.ph w,h=self.w*pw,self.h*ph px=x*pw if type(x)==int else x py=y*ph if type(y)==int else y #center to the area: (if specified) if X!=None: px+=(((X if type(X)==float else float(X)*pw)-px)/2)-w/2 if Y!=None: py+=(((Y if type(Y)==float else float(Y)*ph)-py)/2)-h/2 self.x,self.y=px,py#+h self.X,self.Y=px+w,py+h self.last=(x,y,X,Y) return True else: return False def Color(self,r,g,b,a): if (self.r,self.g,self.b,self.a)!=(r,g,b,a): self.r,self.g,self.b,self.a=r,g,b,a; return True else: return False def __init__(self): self.strings={} def HasString(self,Name): if Name in self.strings: return self.strings[Name].enabled else: return False def AddString(self,pw,ph,Name,text,size,x,y,X=None,Y=None,color=(0,0,0,255)): if Name not in self.strings: #add the string only if needed fcm=1./255 #TODO: remove pw and ph requirements import pygame as pyg from OpenGL import GL F=pyg.font.Font('fonts/tahoma.ttf',size) #don't use .fon files _w,_h=F.size(text); w,h=_w*pw,_h*ph r,g,b,a = color #basic black BG, white FG with antialize: image=pyg.transform.flip(F.render(text,True,(255,255,255),(0,0,0)),False, True).get_buffer().raw #get raw RGB pixel data px=x*pw if type(x)==int else x py=y*ph if type(y)==int else y #center to the area: (if specified) if X!=None: px+=(((X if type(X)==float else float(X)*pw)-px)/2)-w/2 if Y!=None: py+=(((Y if type(Y)==float else float(Y)*ph)-py)/2)-h/2 #''' #Pixel Drawing self.strings[Name]=self._String(image,r*fcm,g*fcm,b*fcm,a*fcm,px,py+h,0,0,_w,_h) ''' texid = GL.glGenTextures(1) GL.glBindTexture( GL.GL_TEXTURE_2D, texid ) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT,1) # glTexImage2D(target, level, internalformat, width, height, border, format, type, data) GL.glTexImage2D( GL.GL_TEXTURE_2D, 0, GL.GL_LUMINANCE_ALPHA, w, h, 0, GL.GL_ALPHA, GL.GL_UNSIGNED_BYTE, image ) GL.glTexParameterf( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR ) GL.glTexParameterf( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR ) GL.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_DECAL) self.strings[Name]=self._String(texid,r*fcm,g*fcm,b*fcm,a*fcm,px,py,px+w,py+h,_w,_h) #''' del(image) #remove the old pyg buffer else: self.strings[Name].enabled=True def RemoveString(self,Name): self.strings[Name].enabled=False def __init__(self): self.stack={} #draws FG before BG with FG over BG (alphas are not mixed) self.overlay={} #draws over the stack (alphas are mixed) self.font={} #same as Overly #NOTE: overlay[1] draws over font[0] def AddStack(self): self.stack[len(self.stack)]=self._PrimitiveCollector() def AddOverlay(self): self.overlay[len(self.overlay)]=self._PrimitiveCollector() self.font[len(self.font)]=self._FontCollector() def clear(self): self.stack={} self.overlay={} self.font={} self.AddStack() self.AddOverlay() layer={} #GUI layering info (collection buffers) layer[0]=__Layer() #updated once, modified, and reused (this is the main layer) layer[0].AddStack() layer[0].AddOverlay() #Drawing Order: #layer[0] # stack[0] #BG # primitive[0] # primitive[1] # primitive[2] # stack[1] #FG (not influenced by BG) # primitive[0] #these primitives are drawn first with a depth of ((len(stack)-stack_index)*.01) # primitive[1] # # overlay[0] #a layer drawn over the stack-layer # primitive[0] # primitive[1] # font[0] #the font that goes over this overlay-layer # text[0] # text[1] # text[2] # # overlay[1] #overlays previous font, overlay, and stack # primitive[0] # primitive[1] # font[1] # text[0] # #layer[1] #(used for browsers, errors, and other popups) # stack[0] #overlays layer[0] # primitive[0] # stack[1] # primitive[0] # # overlay[0] # primitive[0] # font[0] # text[0] # # overlay[1] # primitive[0] # font[1] # text[0] #this contains the info for each widget Widgets = {} motionx,motiony=None,None movementx,movementy=None,None AllowHitUpdates=True; noRelease=False global __AllowVIEWERControl;__AllowVIEWERControl=True #----------------------------------- #main Widgets def __RemoveDropBox(Na): global Widgets,layer try: Widgets[Na].hitdef.enabled=False #disable the hitdef (save the state) sbna='SelectBox%sQuad'%Na sbfna='SelectBox%sText'%Na sbbna='SelectBox%sButtonQuad'%Na sbbdna='SelectBox%sButtonDecal'%Na if layer[0].stack[2].HasPrimitive(sbna): layer[0].stack[2].RemovePrimitive(sbna) layer[0].font[0].RemoveString(sbfna) layer[0].stack[2].RemovePrimitive(sbbna) layer[0].stack[3].RemovePrimitive(sbbdna) except: pass def __DropBox(X,Y,W,Na,Items,Def=0,Text=''): #__SelectBox global Widgets,layer,pw,ph global AllowHitUpdates,noRelease global pw15,pw5, ph20,ph2 #minor pre-calculations X2,Y2 = X+(pw*W),Y+ph20 sy = Y2-Y hsy=sy/2 hsx2 = ((X2+pw15)-X2)/2 #verify the widget exists try: W=Widgets[Na] except KeyError: Widgets[Na]=__Widget() W=Widgets[Na] W.info=[Def,False] #[selectionID,isOpen] W.hitdef.x=X; W.hitdef.y=Y; W.hitdef.X=X2+pw15; W.hitdef.Y=Y2 #update the HitDef if changed by an outside function if AllowHitUpdates!=W.hitdef.enabled: W.hitdef.enabled=AllowHitUpdates #drawing data: sbna='SelectBox%sQuad'%Na sbfna='SelectBox%sText'%Na sbbna='SelectBox%sButtonQuad'%Na sbbdna='SelectBox%sButtonDecal'%Na if not layer[0].stack[2].HasPrimitive(sbna): #don't draw if we already have layer[0].stack[2].AddQuad(sbna,[X,Y],[X2,Y],[X2,Y2],[X,Y2],(175,175,175,180)) layer[0].font[0].AddString(pw,ph,sbfna,Text,12,X+pw5,Y+ph2,None,None,(0,0,0,100)) layer[0].stack[2].AddQuad(sbbna,[X2,Y],[X2+pw15,Y],[X2+pw15,Y2],[X2,Y2],(95,95,95,180)) layer[0].stack[3].AddTri(sbbdna,[X2+pw5,(Y+hsy)-ph2],[(X2+pw15)-pw5,(Y+hsy)-ph2],[X2+hsx2,(Y+hsy)+ph2], (63,63,63,180)) SB = layer[0].stack[2].primitives[sbna] SBF = layer[0].font[0].strings[sbfna] SBB = layer[0].stack[2].primitives[sbbna] SBBD = layer[0].stack[3].primitives[sbbdna] #Positioning Verification if SB.Position([X,Y],[X2,Y],[X2,Y2],[X,Y2]): SBF.Position(pw,ph,X+pw5,Y+ph2,None,None) SBB.Position([X2,Y],[X2+pw15,Y],[X2+pw15,Y2],[X2,Y2]) SBBD.Position([X2+pw5,(Y+hsy)-ph2],[(X2+pw15)-pw5,(Y+hsy)-ph2],[X2+hsx2,(Y+hsy)+ph2]) #HitDef if W.hitdef.x!=X: W.hitdef.x=X; W.hitdef.X=X2+pw15 if W.hitdef.y!=Y: W.hitdef.y=Y; W.hitdef.Y=Y2 #Widget logic if W.event.hasFocus: #change the color if the mouse is over the selection box if W.event.clickL or W.event.holdL: #change the color if the selection box is clicked or held SBB.Color(79,79,79,180) else: SBB.Color(87,87,87,180) else: SBB.Color(95,95,95,180) if W.event.releaseL: W.info[1]=True #isOpen = True State = W.info if State[1]: #the box has been clicked AllowHitUpdates=False #prevent hit updates from other widgets #(once we've made our selection, we can then allow hit updates) remove=False for i,v in enumerate(Items): #generate a custom widget name using the main name, the item's text, and the enumerant value N = '%s_%s_Sel%i'%(Na,v,i) #minor pre-calculations yp=(sy*(i+1)) x1,y1,x2,y2=X,Y+yp,X2,Y2+yp #we have to create a new widget for each entry here #verify the widget exists try: sW=Widgets[N] except KeyError: Widgets[N]=__Widget() sW=Widgets[N] sW.info=[Def,False] #[selectionID,isOpen] sW.hitdef.x=x1; sW.hitdef.y=y1; sW.hitdef.X=x2; sW.hitdef.Y=y2 #HitDefs created at this point are always active #drawing data: sbsbna='SelectionButton%s'%N sbsfna='SelectionFont%s'%N if not layer[0].overlay[0].HasPrimitive(sbsbna): layer[0].overlay[0].AddQuad(sbsbna,[x1,y1],[x2,y1],[x2,y2],[x1,y2],(0,0,0,127)) layer[0].font[0].AddString(pw,ph,sbsfna,v,12,x1+pw5,y1+ph2,None,None,(255,255,255,100)) sB=layer[0].overlay[0].primitives[sbsbna] sF=layer[0].font[0].strings[sbsfna] #we don't need to verify the positioning here... (nothing can be moved at this point) #Widget logic if sW.event.hasFocus: if sW.event.clickL or sW.event.holdL: sB.Color(127,127,127,127); sF.Color(0,0,0,100) else: sB.Color(191,191,191,127); sF.Color(0,0,0,100) else: sB.Color(0,0,0,127); sF.Color(255,255,255,100) #apply the selection and set to remove these widgets when LMB is released if sW.event.releaseL: W.info=[i,False]; remove=True #add a few widgets to define the click-off area #(anywhere on the screen that's not in this widget's range) # ^clicking will close the widget and keep it at it's current selection _DAN=['%s_DeActivator%i'%(Na,i) for i in range(4)] #custom deactivator names #test if these widgets exist try: R0=Widgets[_DAN[0]]; R1=Widgets[_DAN[1]]; R2=Widgets[_DAN[2]]; R3=Widgets[_DAN[3]] except KeyError: Widgets[_DAN[0]]=__Widget() Widgets[_DAN[1]]=__Widget() Widgets[_DAN[2]]=__Widget() Widgets[_DAN[3]]=__Widget() R0=Widgets[_DAN[0]]; R1=Widgets[_DAN[1]]; R2=Widgets[_DAN[2]]; R3=Widgets[_DAN[3]] R0.hitdef.x=0.0;R0.hitdef.y=0.0;R0.hitdef.X=X ;R0.hitdef.Y=1.0 #left R1.hitdef.x=X2 ;R1.hitdef.y=0.0;R1.hitdef.X=1.0;R1.hitdef.Y=1.0 #right R2.hitdef.x=X ;R2.hitdef.y=0.0;R2.hitdef.X=X2 ;R2.hitdef.Y=Y2 #top (Y2 because the main widget has no control here) R3.hitdef.x=X ;R3.hitdef.y=y2 ;R3.hitdef.X=X2 ;R3.hitdef.Y=1.0 #bottom #the logic to test for and execute a click-off (from any mouse button) if any([R0.event.clickL,R0.event.clickM,R0.event.clickR, R1.event.clickL,R1.event.clickM,R1.event.clickR, R2.event.clickL,R2.event.clickM,R2.event.clickR, R3.event.clickL,R3.event.clickM,R3.event.clickR]): W.info[1]=False #isOpen = False remove=True #we don't need any positioning verification if remove: #remove the selection widgets and click-off widgets for i,v in enumerate(Items): N='%s_%s_Sel%i'%(Na,v,i); sbsbna='SelectionButton%s'%N; sbsfna='SelectionFont%s'%N layer[0].overlay[0].RemovePrimitive(sbsbna); layer[0].font[0].RemoveString(sbsfna) Widgets.pop(N) Widgets.pop(_DAN[0]) #left Widgets.pop(_DAN[1]) #right Widgets.pop(_DAN[2]) #top Widgets.pop(_DAN[3]) #bottom AllowHitUpdates=True return State[0] def __RemoveTButton(Na): global Widgets,layer try: Widgets[Na].hitdef.enabled=False #disable the hitdef (save the state) tbna='TButton%sQuad'%Na tbfna='TButton%sText'%Na if layer[0].stack[2].HasPrimitive(tbna): layer[0].stack[2].RemovePrimitive(tbna) layer[0].font[0].RemoveString(tbfna) except: pass def __TButton(X,Y,Na,St=False,Text='',fontcolor=(0,0,0,255)): global Widgets,layer,pw,ph global AllowHitUpdates global pw25,pw20, ph20,ph2 #minor pre-calculations X2,Y2=X+pw20,Y+ph20 fx,fy=X+pw25,Y+ph2 #verify the widget exists try: W=Widgets[Na] except KeyError: Widgets[Na]=__Widget() W=Widgets[Na] W.info=St #toggle state W.hitdef.x=X; W.hitdef.y=Y; W.hitdef.X=X+pw20; W.hitdef.Y=Y+ph20 #update the HitDef if changed by an outside function if AllowHitUpdates!=W.hitdef.enabled: W.hitdef.enabled=AllowHitUpdates #drawing data: tbna='TButton%sQuad'%Na tbfna='TButton%sText'%Na if not layer[0].stack[2].HasPrimitive(tbna): #don't draw if we already have layer[0].stack[2].AddQuad(tbna,[X,Y],[X2,Y],[X2,Y2],[X,Y2],(95,95,95,180)) layer[0].font[0].AddString(pw,ph,tbfna,Text,12,fx,fy,None,None,fontcolor) TB = layer[0].stack[2].primitives[tbna] TBF = layer[0].font[0].strings[tbfna] #Positioning Verification if TB.Position([X,Y],[X2,Y],[X2,Y2],[X,Y2]): TBF.Position(pw,ph,fx,fy,None,None) #HitDef if W.hitdef.x!=X: W.hitdef.x=X; W.hitdef.X=X2 if W.hitdef.y!=Y: W.hitdef.y=Y; W.hitdef.Y=Y2 #Widget logic if W.info: if W.event.hasFocus: #change the color if the mouse is over the selection box if W.event.clickL or W.event.holdL: #change the color if the selection box is clicked or held TB.Color(79,79,79,180) else: TB.Color(95,95,95,180) else: TB.Color(79,79,79,180) else: if W.event.hasFocus: if W.event.clickL or W.event.holdL: TB.Color(79,79,79,180) else: TB.Color(111,111,111,180) else: TB.Color(95,95,95,180) if W.event.releaseL: W.info=(False if W.info else True) return W.info def __RemoveButton(Na): global Widgets,layer try: Widgets[Na].hitdef.enabled=False #disable the hitdef (save the state) bna='Button%sQuad'%Na bfna='Button%sText'%Na if layer[0].stack[2].HasPrimitive(bna): layer[0].stack[2].RemovePrimitive(bna) layer[0].font[0].RemoveString(bfna) except: pass def __Button(X1,Y1,X2,Y2,Na,Text='',Hint='',fontcolor=(0,0,0,255),St=False): global Widgets,pw,ph,AllowHitUpdates,layer #verify the widget exists try: W=Widgets[Na] except KeyError: Widgets[Na]=__Widget() W=Widgets[Na] W.info=['button',St] W.hitdef.x=X1; W.hitdef.y=Y1; W.hitdef.X=X2; W.hitdef.Y=Y2 #update the HitDef if changed by an outside function if AllowHitUpdates!=W.hitdef.enabled: W.hitdef.enabled=AllowHitUpdates #drawing data: bna='Button%sQuad'%Na bfna='Button%sText'%Na if not layer[0].stack[2].HasPrimitive(bna): #don't draw if we already have layer[0].stack[2].AddQuad(bna,[X1,Y1],[X2,Y1],[X2,Y2],[X1,Y2],(95,95,95,200)) layer[0].font[0].AddString(pw,ph,bfna,Text,12,X1,Y1,X2,Y2,fontcolor) B = layer[0].stack[2].primitives[bna] BF = layer[0].font[0].strings[bfna] #Positioning Verification if B.Position([X1,Y1],[X2,Y1],[X2,Y2],[X1,Y2]): BF.Position(pw,ph,X1,Y1,X2,Y2) #HitDef if W.hitdef.x!=X1: W.hitdef.x=X1 if W.hitdef.y!=Y1: W.hitdef.y=Y1 if W.hitdef.X!=X2: W.hitdef.X=X2 if W.hitdef.Y!=Y2: W.hitdef.Y=Y2 #Widget logic if W.event.hasFocus: #change the color if the mouse is over the button if W.event.clickL or W.event.holdL: #change the color if the button is clicked or held B.Color(79,79,79,200) else: B.Color(87,87,87,200) else: B.Color(95,95,95,200) if W.event.releaseL: W.info[1]=True #set the button state as True upon release return W.info[1] def __EndButton(Na): #sets button state as False try: if type(Widgets[Na].info)==list: #verify this name points to a button: if Widgets[Na].info[0]=='button': Widgets[Na].info[1]=False except KeyError: pass #this button may not yet be defined def __RemoveScrollbar(Na): global Widgets,layer try: Widgets[Na].hitdef.enabled=False #disable the hitdef (save the state) sbtna='ScrollBar%sTrack'%Na sbbna='ScrollBar%sButton'%Na if layer[0].stack[2].HasPrimitive(sbtna): layer[0].stack[2].RemovePrimitive(sbtna) layer[0].stack[3].RemovePrimitive(sbbna) except: pass def __Scrollbar(X,Y,S,R,Na,y=False): global Widgets,AllowHitUpdates,layer,movementx,movementy global pw,ph, pw15, ph15 #TODO: # - scrollbar-track hitdefs # - R = float() #verify the widget exists try: W=Widgets[Na] except KeyError: Widgets[Na]=__Widget() W=Widgets[Na] W.info=0 #update the HitDef if changed by an outside function if AllowHitUpdates!=W.hitdef.enabled: W.hitdef.enabled=AllowHitUpdates if not W.motion: W.motion=True #minor pre-calculations BPX1,BPY1,BPX2,BPY2=X,Y,X+pw15,Y+ph15 P=W.info if y: p=P*ph; Y2=Y+S; X2=BPX2; BPY1+=p; BPY2+=p; PR=ph else: p=P*pw; X2=X+S; Y2=BPY2; BPX1+=p; BPX2+=p; PR=pw #drawing data: sbtna='ScrollBar%sTrack'%Na sbbna='ScrollBar%sButton'%Na if not layer[0].stack[2].HasPrimitive(sbtna): #don't draw if we already have layer[0].stack[2].AddQuad(sbtna,[X,Y],[X2,Y],[X2,Y2],[X,Y2], (95,95,95,180)) layer[0].stack[3].AddQuad(sbbna,[BPX1,BPY1],[BPX2,BPY1],[BPX2,BPY2],[BPX1,BPY2],(143,143,143,180)) SBT=layer[0].stack[2].primitives[sbtna] SBB=layer[0].stack[3].primitives[sbbna] #Positioning Verification SBT.Position([X,Y],[X2,Y],[X2,Y2],[X,Y2]) SBB.Position([BPX1,BPY1],[BPX2,BPY1],[BPX2,BPY2],[BPX1,BPY2]) #HitDef if W.hitdef.x!=BPX1: W.hitdef.x=BPX1; W.hitdef.X=BPX2 if W.hitdef.y!=BPY1: W.hitdef.y=BPY1; W.hitdef.Y=BPY2 #Widget logic if W.event.hasFocus: #change the color if the mouse is over the button if W.event.clickL or W.event.holdL: #change the color if the button is clicked or held SBB.Color(159,159,159,180) else: SBB.Color(175,175,175,180) else: SBB.Color(167,167,167,180) m,s = (movementy,int(S/ph)-15) if y else (movementx,int(S/pw)-15) if W.event.holdL: if m!=None: W.info=m-(Y/ph) if y else m-(X/pw) if W.info>s: W.info=s elif W.info<0: W.info=0 #scale the range itself: return -(int(R*((1./s)*W.info))*PR) # -(int(200*0.5)*pw) = -100 (shift left by 100 pixels) #----------------------------------- #panel drawing functions and sub-functions def __RemoveModelManageTab(): __RemoveButton("ModelImportButton") __RemoveScrollbar('ModelManageTabSBar') def __DrawModelManageTab(): __RemoveModelFeaturesTab() __RemoveModelExportTab() global pw172,pw140,pw40, ph104,ph72,ph52 P=__Scrollbar(pw172,ph52,1.-ph104,240,'ModelManageTabSBar',True) if __Button(pw40,ph52+P,pw140,ph72+P,"ModelImportButton","Import","",(230,230,230,255)): __EndButton("ModelImportButton") def __DrawModelFeaturesTab(): __RemoveModelManageTab() __RemoveModelExportTab() pass def __RemoveModelFeaturesTab(): pass def __DrawModelExportTab(): __RemoveModelManageTab() __RemoveModelFeaturesTab() #__BrowseBar(pw10,ph40,180) #Model Export Path pass def __RemoveModelExportTab(): pass ActiveModelTab=0 def __RemoveModelPanel(): global ActiveModelTab __RemoveButton("ModelManageSlot") __RemoveButton("ModelFeaturesSlot") __RemoveButton("ModelExportSlot") if ActiveModelTab==0: __RemoveModelManageTab() elif ActiveModelTab==1: __RemoveModelFeaturesTab() elif ActiveModelTab==2: __RemoveModelExportTab() def __ModelPanel(): global ActiveModelTab global pw210,pw160,pw50, ph83,ph82,ph63,ph62,ph42,ph41,ph21,ph20 MB0 = __Button(0.,ph21,pw210,ph41,"ModelManageSlot","Models","",(230,230,230,255),True) MB1 = __Button(0.,(1.-ph41 if MB0 else ph42), pw210,(1.-ph21 if MB0 else ph62),"ModelFeaturesSlot","Features","",(230,230,230,255)) MB2 = __Button(0.,(1.-ph20 if MB0 or MB1 else ph63), pw210,(1. if MB0 or MB1 else ph83),"ModelExportSlot","Export","",(230,230,230,255)) if MB0 and MB1: #switch logic if ActiveModelTab==0: ActiveModelTab=1; __EndButton("ModelManageSlot") else: ActiveModelTab=0; __EndButton("ModelFeaturesSlot") if MB0 and MB2: if ActiveModelTab==0: ActiveModelTab=2; __EndButton("ModelManageSlot") else: ActiveModelTab=0; __EndButton("ModelExportSlot") if MB1 and MB2: if ActiveModelTab==1: ActiveModelTab=2; __EndButton("ModelFeaturesSlot") else: ActiveModelTab=1; __EndButton("ModelExportSlot") #draw widgets based on the active button if ActiveModelTab==0: __DrawModelManageTab() elif ActiveModelTab==1: __DrawModelFeaturesTab() elif ActiveModelTab==2: __DrawModelExportTab() def __DrawAnimManageTab(): __RemoveAnimFeaturesTab() __RemoveAnimExportTab() global pw160,pw50, ph82,ph62 if __Button(1.-pw160,ph62,1.-pw50,ph82,"AnimImportButton","Import","",(230,230,230,255)): __EndButton("AnimImportButton") def __RemoveAnimManageTab(): __RemoveButton("AnimImportButton") def __DrawAnimFeaturesTab(): __RemoveAnimManageTab() __RemoveAnimExportTab() pass def __RemoveAnimFeaturesTab(): pass def __DrawAnimExportTab(): __RemoveAnimManageTab() __RemoveAnimFeaturesTab() #__BrowseBar(pw10,ph40,180) #Anim Export Path pass def __RemoveAnimExportTab(): pass ActiveAnimTab=0 def __RemoveAnimPanel(): global ActiveAnimTab __RemoveButton("AnimManageSlot") __RemoveButton("AnimFeaturesSlot") __RemoveButton("AnimExportSlot") if ActiveAnimTab==0: __RemoveAnimManageTab() elif ActiveAnimTab==1: __RemoveAnimFeaturesTab() elif ActiveAnimTab==2: __RemoveAnimExportTab() def __AnimPanel(): global pw,ph,ActiveAnimTab global pw210,pw160,pw50, ph83,ph82,ph63,ph62,ph42,ph41,ph21,ph20 #__ExPanel(pw*0,ph*21,pw*210,ph*h,1,'MODEL') AB0 = __Button(1.-pw210,ph21,1.,ph41,"AnimManageSlot","Animations","",(230,230,230,255),True) AB1 = __Button(1.-pw210,(1.-ph41 if AB0 else ph42), 1.,(1.-ph21 if AB0 else ph62),"AnimFeaturesSlot","Features","",(230,230,230,255)) AB2 = __Button(1.-pw210,(1.-ph20 if AB0 or AB1 else ph63), 1.,(1. if AB0 or AB1 else ph83),"AnimExportSlot","Export","",(230,230,230,255)) if AB0 and AB1: #switch logic if ActiveAnimTab==0: ActiveAnimTab=1; __EndButton("AnimManageSlot") else: ActiveAnimTab=0; __EndButton("AnimFeaturesSlot") if AB0 and AB2: if ActiveAnimTab==0: ActiveAnimTab=2; __EndButton("AnimManageSlot") else: ActiveAnimTab=0; __EndButton("AnimExportSlot") if AB1 and AB2: if ActiveAnimTab==1: ActiveAnimTab=2; __EndButton("AnimFeaturesSlot") else: ActiveAnimTab=1; __EndButton("AnimExportSlot") #draw widgets based on the active button if ActiveAnimTab==0: __DrawAnimManageTab() elif ActiveAnimTab==1: __DrawAnimFeaturesTab() elif ActiveAnimTab==2: __DrawAnimExportTab() def __RemoveDisplayPanel(): __RemoveTButton('EnLight') __RemoveTButton('EnWire') __RemoveDropBox('Draw Bones') __RemoveDropBox('Display') __RemoveDropBox('Projection') __RemoveDropBox('3D Drawing') __RemoveDropBox('Colors') __RemoveDropBox('Freq') __RemoveScrollbar('DisplayPanelSBar') def __DisplayPanel(X1,X2): global pw251,pw131,pw11, ph111,ph81,ph56,ph31 global pw #minor pre-calculations pwX1251 = X1+pw251 pwX1131 = X1+pw131 pwX111 = X1+pw11 V=__Scrollbar(pwX111,ph111,(X2-pwX111)-pw11,0,'DisplayPanelSBar') VIEWER.TOGGLE_LIGHTING=__TButton(pwX111,ph31,'EnLight',True,'Lighting') VIEWER.TOGGLE_WIREFRAME=__TButton(pwX111,ph56,'EnWire',False,'Wireframe') VIEWER.TOGGLE_BONES=__DropBox(pwX111,ph81,100,'Draw Bones',['None','Standard','Overlay (X-Ray)'],0) #reversed drawing order left if VIEWER.TOGGLE_3D==2: __RemoveDropBox('Colors'); VIEWER.TOGGLE_3D_MODE[1]=[1./60,1./120][__DropBox(pwX1251,ph81,50,'Freq',['60hz','120hz'],0)] if VIEWER.TOGGLE_3D==1: __RemoveDropBox('Freq'); VIEWER.TOGGLE_3D_MODE[0]=__DropBox(pwX1251,ph81,50,'Colors',['R|GB','G|RB','B|RG'],0) VIEWER.TOGGLE_3D=__DropBox(pwX1131,ph81,100,'3D Drawing',['Off','Analglyph','Shutter'],0) VIEWER.TOGGLE_ORTHO=__DropBox(pwX1131,ph56,100,'Projection',['Perspective','Orthographic'],1) VIEWER.TOGGLE_GRID=[2 if VIEWER.TOGGLE_GRID>2 else VIEWER.TOGGLE_GRID,3,4][__DropBox(pwX1131,ph31,100,'Display',['Grid','Floor','Off'],0)] def __RemoveControlPanel(): pass def __ControlPanel(X1,X2): pass def __DrawOptionsData(): global layer #options go here def __RemoveOptionsData(): global layer def __DrawUpdateData(): global layer,pw,ph global ph20 if not layer[0].font[0].HasString('UpdateDevelopmentString'): layer[0].font[0].AddString(pw,ph,'UpdateDevelopmentString', "The Update system is still in development.", 16,0.0,0.0,1.0,1-ph20,(0,0,0,127)) def __RemoveUpdateData(): #verify if anything is used by the update panel and remove it if so. global layer if layer[0].font[0].HasString('UpdateDevelopmentString'): layer[0].font[0].RemoveString('UpdateDevelopmentString') def __OpenOptionsUpdatePanel(): global pw,ph global pw13,pw10,pw7, ph20,ph14,ph13,ph7,ph6 #update the decal coords to match the button positions OBD=layer[0].stack[3].primitives['OptionButtonDecal'] UND=layer[0].stack[3].primitives['UpdateNotificationDecal'] #move to bottom OBD.Position([0.5-pw10,1-ph6],[0.5+pw10,1-ph6],[0.5,1-ph14]) UND.Position([1-pw13,1-ph13],[1-pw7,1-ph13],[1-pw7,1-ph7],[1-pw13,1-ph7]) def __CloseOptionsUpdatePanel(): global pw,ph global pw13,pw10,pw7, ph20,ph14,ph13,ph7,ph6 if layer[0].stack[0].HasPrimitive('OptionsUpdatePanelBG'): #remove the BG layer[0].stack[0].RemovePrimitive('OptionsUpdatePanelBG') __RemoveUpdateData(); __RemoveOptionsData() #remove any active display data #update the decal coords to match the button positions OBD=layer[0].stack[3].primitives['OptionButtonDecal'] UND=layer[0].stack[3].primitives['UpdateNotificationDecal'] #move buttons to top OBD.Position([0.5-pw10,ph6],[0.5+pw10,ph6],[0.5,ph14]) UND.Position([1-pw13,ph7],[1-pw7,ph7],[1-pw7,ph13],[1-pw13,ph13]) OptionsUpdatePanelExpensionState=False #long var names won't easily get used OptionsUpdatePanelButton=0 #ID of current button pressed (used when clicking another button) def __OptionsUpdatePanel(): global pw,ph,OptionsUpdatePanelExpensionState,OptionsUpdatePanelButton,layer global pw21,pw20,pw13,pw10,pw7, ph20,ph14,ph13,ph7,ph6 PES=OptionsUpdatePanelExpensionState #short local name from long global name #verify we have the needed stack layers for drawing #layer[0].stack[0] is used for basic BG drawing try: layer[0].stack[1] #used for sub-BG widgets such as scroll-boxes except KeyError: layer[0].AddStack() try: layer[0].stack[2] #used for basic overlay widgets such as buttons except KeyError: layer[0].AddStack() try: layer[0].stack[3] #used for special decals drawn on overlay widgets except KeyError: layer[0].AddStack() if not layer[0].stack[3].HasPrimitive('OptionButtonDecal'): if PES: layer[0].stack[3].AddTri('OptionButtonDecal', [0.5-pw10,1-ph6],[0.5+pw10,1-ph6],[0.5,1-ph14], (63,63,63,180)) layer[0].stack[3].AddQuad('UpdateNotificationDecal', [1-pw13,1-ph13],[1-pw7,1-ph13],[1-pw7,1-ph7],[1-pw13,1-ph7], (255,63,63,200)) else: layer[0].stack[3].AddTri('OptionButtonDecal', [0.5-pw10,ph6],[0.5+pw10,ph6],[0.5,ph14], (63,63,63,180)) layer[0].stack[3].AddQuad('UpdateNotificationDecal', [1-pw13,ph7],[1-pw7,ph7],[1-pw7,ph13],[1-pw13,ph13], (255,63,63,200)) if PES: #option/update panel is expanded: Y = 1.0 ''' if OptionsUpdatePanelButton==0: #options panel drawing: __RemoveUpdateData(); __DrawOptionsData() elif OptionsUpdatePanelButton==1: #update panel drawing: __RemoveOptionsData(); __DrawUpdateData() ''' if not layer[0].stack[0].HasPrimitive('OptionsUpdatePanelBG'): #create the BG layer[0].stack[0].AddQuad('OptionsUpdatePanelBG', [0.0,0.0],[1.0,0.0],[1.0,1-ph20],[0.0,1-ph20], (127,127,127,200)) else: #create new or modify existing decals Y = ph20 if __Button(0.0,Y-ph20,1-pw21,Y,"OptionsPanelToggle","","Options",(230,230,230,200)): if not OptionsUpdatePanelExpensionState: #open panel OptionsUpdatePanelExpensionState=True OptionsUpdatePanelButton=0 __OpenOptionsUpdatePanel() __DrawOptionsData() elif OptionsUpdatePanelButton==0: #close panel OptionsUpdatePanelExpensionState=False __RemoveOptionsData() __CloseOptionsUpdatePanel() else: #switch to options OptionsUpdatePanelButton=0 __RemoveUpdateData() __DrawOptionsData() __EndButton("OptionsPanelToggle") if __Button(1-pw20,Y-ph20,1.0,Y,"UpdatePanelToggle","","Updates",(230,230,230,200)): if not OptionsUpdatePanelExpensionState: #open panel OptionsUpdatePanelExpensionState=True OptionsUpdatePanelButton=1 __OpenOptionsUpdatePanel() __DrawUpdateData() elif OptionsUpdatePanelButton==1: #close panel OptionsUpdatePanelExpensionState=False __RemoveUpdateData() __CloseOptionsUpdatePanel() else: #switch to update OptionsUpdatePanelButton=1 __RemoveOptionsData() __DrawUpdateData() __EndButton("UpdatePanelToggle") return PES #----------------------------------- def __RemoveExPanel(Na): global Widgets,layer try: Widgets[Na].hitdef.enabled=False #disable the hitdef (save the state) ebna='EButton%sQuad'%Na ebdna='EButton%sDecal'%Na if layer[0].stack[2].HasPrimitive(ebna): layer[0].stack[2].RemovePrimitive(ebna) layer[0].stack[3].RemovePrimitive(ebdna) if layer[0].stack[0].HasPrimitive(Na): layer[0].stack[0].RemovePrimitive(Na) except: pass def __ExPanel(X1,Y1,X2,Y2,EB,Na,MX=0.,MY=0.,St=True): #returns current state for other panels #MX and XY are for outside influence on the toggle button global Widgets,layer,pw,ph global AllowHitUpdates global pw35,pw30,pw25,pw15,pw10,pw5, ph35,ph30,ph25,ph15,ph10,ph5 #minor pre-calculations sx=X2-X1; sy=Y2-Y1 #verify the widget exists try: W=Widgets[Na] except KeyError: Widgets[Na]=__Widget() W=Widgets[Na] W.info=St #toggle state #update the HitDef if changed by an outside function if AllowHitUpdates!=W.hitdef.enabled: W.hitdef.enabled=AllowHitUpdates S=W.info #60x15px rectangle calculations (toggle button) if (EB==0 and S) or (EB==2 and not S): #top xpos=X1+(sx/2)+MX EBX1,EBY1,EBX2,EBY2=xpos-pw30,Y1,xpos+pw30,Y1+ph15 TPX1,TPY1,TPX2,TPY2,TPX3,TPY3=xpos,Y1+ph10,xpos-pw5,Y1+ph5,xpos+pw5,Y1+ph5 elif (EB==1 and S) or (EB==3 and not S): #right ypos=Y1+(sy/2)+MY EBX1,EBY1,EBX2,EBY2=X2-pw15,ypos-ph30,X2,ypos+ph30 TPX1,TPY1,TPX2,TPY2,TPX3,TPY3=X2-pw10,ypos,X2-pw5,ypos-pw5,X2-pw5,ypos+pw5 elif (EB==2 and S) or (EB==0 and not S): #bottom xpos=X1+(sx/2)+MX EBX1,EBY1,EBX2,EBY2=xpos-pw30,Y2-ph15,xpos+pw30,Y2 TPX1,TPY1,TPX2,TPY2,TPX3,TPY3=xpos,Y2-ph10,xpos+pw5,Y2-ph5,xpos-pw5,Y2-ph5 elif (EB==3 and S) or (EB==1 and not S): #left ypos=Y1+(sy/2)+MY EBX1,EBY1,EBX2,EBY2=X1,ypos-ph30,X1+pw15,ypos+ph30 TPX1,TPY1,TPX2,TPY2,TPX3,TPY3=X1+pw10,ypos,X1+pw5,ypos-pw5,X1+pw5,ypos+pw5 #drawing data: ebna='EButton%sQuad'%Na ebdna='EButton%sDecal'%Na if not layer[0].stack[2].HasPrimitive(ebna): #don't draw if we already have layer[0].stack[2].AddQuad(ebna,[EBX1,EBY1],[EBX2,EBY1],[EBX2,EBY2],[EBX1,EBY2],(95,95,95,200)) layer[0].stack[3].AddTri(ebdna,[TPX1,TPY1],[TPX2,TPY2],[TPX3,TPY3],(63,63,63,180)) if S: #is the panel expanded? if not layer[0].stack[0].HasPrimitive(Na): #add the BG layer[0].stack[0].AddQuad(Na,[X1,Y1],[X2,Y1],[X2,Y2],[X1,Y2],(127,127,127,200)) else: #remove the BG if layer[0].stack[0].HasPrimitive(Na): layer[0].stack[0].RemovePrimitive(Na) B = layer[0].stack[2].primitives[ebna] BD = layer[0].stack[3].primitives[ebdna] #Positioning Verification if B.Position([EBX1,EBY1],[EBX2,EBY1],[EBX2,EBY2],[EBX1,EBY2]): BD.Position([TPX1,TPY1],[TPX2,TPY2],[TPX3,TPY3]) if layer[0].stack[0].HasPrimitive(Na): layer[0].stack[0].primitives[Na].Position([X1,Y1],[X2,Y1],[X2,Y2],[X1,Y2]) #HitDef if W.hitdef.x!=EBX1: W.hitdef.x=EBX1; W.hitdef.X=EBX2 if W.hitdef.y!=EBY1: W.hitdef.y=EBY1; W.hitdef.Y=EBY2 #Widget logic if W.event.hasFocus: #change the color if the mouse is over the button if W.event.clickL or W.event.holdL: #change the color if the button is clicked or held B.Color(79,79,79,200) else: B.Color(87,87,87,200) else: B.Color(95,95,95,200) if W.event.releaseL: W.info=not W.info return S #----------------------------------- #input functions: def __FrameCheck(): #where most of the widget-event state-logic happens. #the functions below simply handle base-state functions #a frame must pass before the base state can be reverted (where this function comes in) global Widgets,motionx,motiony,movementx,movementy for WN in Widgets: W=Widgets[WN] #check for a click event: (transfer click to hold) if W.event.clickL: W.event.clickL=False; W.event.holdL=True if W.event.clickM: W.event.clickM=False; W.event.holdM=True if W.event.clickR: W.event.clickR=False; W.event.holdR=True #check for a release event: (disable the hold-state) if W.event.releaseL: W.event.releaseL=False; W.event.holdL=False if W.event.releaseM: W.event.releaseM=False; W.event.holdM=False if W.event.releaseR: W.event.releaseR=False; W.event.holdR=False #check for a scroll event: if W.event.scrollU: W.event.scrollU=False if W.event.scrollD: W.event.scrollD=False #check for a key press event: (transfer press to hold) if W.event.keyPress: W.event.keyPress=False; W.event.keyHold=True #check for a key release event: (disable the hold-state) if W.event.keyRelease: W.event.keyRelease=False; W.event.keyHold=False; W.key=None #check for a mouse-focus event: if W.event.gainFocus: W.event.gainFocus=False; W.event.hasFocus=True if W.event.loseFocus: W.event.loseFocus=False W.event.hasFocus=False #don't remember click events if we lose focus W.event.holdL=False W.event.holdM=False W.event.holdR=False #check for mouse drag and reset: if motionx!=None: motionx=None if motiony!=None: motiony=None if movementx!=None: movementx=None if movementy!=None: movementy=None doFrameCheck=False def __Click(b,x,y): global Widgets,doFrameCheck first=True for WN in Widgets: W=Widgets[WN]; HD=W.hitdef if HD.enabled: X1,Y1,X2,Y2=HD.x,HD.y,HD.X,HD.Y if X1<x<X2 and Y1<y<Y2 and first: # first enabled Widget clicked if b==1: W.event.clickL=True; doFrameCheck=True if b==2: W.event.clickM=True; doFrameCheck=True if b==3: W.event.clickR=True; doFrameCheck=True #scrolling: if b==4: W.event.scrollU=True; doFrameCheck=True if b==5: W.event.scrollD=True; doFrameCheck=True first=False #only perform operations on the first widget def __Release(b,x,y): global Widgets,doFrameCheck,noRelease first=True for WN in Widgets: W=Widgets[WN]; HD=W.hitdef if HD.enabled: X1,Y1,X2,Y2=HD.x,HD.y,HD.X,HD.Y if X1<x<X2 and Y1<y<Y2 and first: # first enabled Widget released if b==1: W.event.releaseL=True; doFrameCheck=True if b==2: W.event.releaseM=True; doFrameCheck=True if b==3: W.event.releaseR=True; doFrameCheck=True #scrolling is managed by "__FrameCheck", so it's not needed here first=False def __Motion(b,x,y,rx,ry): #rx,ry - the number of pixels the mouse has moved (float values) global Widgets,doFrameCheck,motionx,motiony motionx,motiony=rx,ry movementx,movementy=x,y _x=x*pw; _y=y*ph for WN in Widgets: W=Widgets[WN]; HD=W.hitdef if HD.enabled: X1,Y1,X2,Y2=HD.x,HD.y,HD.X,HD.Y if X1<_x<X2 and Y1<_y<Y2: W.event.gainFocus=True; doFrameCheck=True else: if W.event.hasFocus: W.event.loseFocus=True; doFrameCheck=True def __KeyPress(k): global Widgets,doFrameCheck for WN in Widgets: W=Widgets[WN] if W.allowKeys: W.event.keyPress=True; doFrameCheck=True W.key=k def __KeyRelease(k): global Widgets,doFrameCheck for WN in Widgets: W=Widgets[WN] if W.allowKeys: W.event.keyRelease=True; doFrameCheck=True W.key=k #----------------------------------- #main functions: def __ResizeGUI(w,h): global pw,ph,layer #using floats will cause a more accurate edge-blur between panels when the screen is resized pw,ph=1./w,1./h #using ints won't look as pretty, but you won't need the extra calculations (TODO: add in options) #positioning pre-calculations #(1.0/ScreenWidth)*PixelWidth global pw600; pw600 = pw*600 global pw251; pw251 = pw*251 global pw228; pw228 = pw*228 global pw211; pw211 = pw*211 global pw210; pw210 = pw*210 global pw172; pw172 = pw*172 global pw160; pw160 = pw*160 global pw140; pw140 = pw*140 global pw131; pw131 = pw*131 global pw105; pw105 = pw*105 global pw50; pw50 = pw*50 global pw40; pw40 = pw*40 global pw35; pw35 = pw*35 global pw30; pw30 = pw*30 global pw25; pw25 = pw*25 global pw21; pw21 = pw*21 global pw20; pw20 = pw*20 global pw17; pw17 = pw*17 global pw15; pw15 = pw*15 global pw13; pw13 = pw*13 global pw11; pw11 = pw*11 global pw10; pw10 = pw*10 global pw7; pw7 = pw*7 global pw5; pw5 = pw*5 #(1.0/ScreenHeight)*PixelHeight global ph600; ph600 = ph*600 global ph167; ph167 = ph*167 global ph150; ph150 = ph*150 global ph111; ph111 = ph*111 global ph104; ph104 = ph*104 global ph83; ph83 = ph*83 global ph82; ph82 = ph*82 global ph81; ph81 = ph*81 global ph72; ph72 = ph*72 global ph63; ph63 = ph*63 global ph62; ph62 = ph*62 global ph56; ph56 = ph*56 global ph52; ph52 = ph*52 global ph42; ph42 = ph*42 global ph41; ph41 = ph*41 global ph35; ph35 = ph*35 global ph31; ph31 = ph*31 global ph30; ph30 = ph*30 global ph21; ph21 = ph*21 global ph25; ph25 = ph*25 global ph20; ph20 = ph*20 global ph17; ph17 = ph*17 global ph15; ph15 = ph*15 global ph14; ph14 = ph*14 global ph13; ph13 = ph*13 global ph11; ph11 = ph*11 global ph10; ph10 = ph*10 global ph7; ph7 = ph*7 global ph6; ph6 = ph*6 global ph5; ph5 = ph*5 global ph2; ph2 = ph*2 for lid in layer: layer[lid].clear() showHitDefs=0 __TextureCache={} lw,lh = 0,0 def __DrawGUI(RotMatrix): #called directly by the display function after drawing the scene global pw,ph,lw,lh,layer global pw600,pw228,pw211,pw210,pw105,pw17, ph600,ph167,ph150,ph21,ph17,ph11 #the GUI is drawn over the scene by clearing the depth buffer __GL.glMatrixMode(__GL.GL_PROJECTION) __GL.glLoadIdentity() __GL.glOrtho(0.0, 1.0, 1.0, 0.0, -100, 100) __GL.glMatrixMode(__GL.GL_MODELVIEW) __GL.glLoadIdentity() __GL.glClear( __GL.GL_DEPTH_BUFFER_BIT ) __GL.glDisable(__GL.GL_TEXTURE_2D) __GL.glDisable(__GL.GL_LIGHTING) M,A,D,C=False,False,False,False if __OptionsUpdatePanel(): __RemoveModelPanel() __RemoveExPanel('MODEL') __RemoveAnimPanel() __RemoveExPanel('ANIM') __RemoveDisplayPanel() __RemoveExPanel('DSPL') __RemoveControlPanel() __RemoveExPanel('CTRL') else: M = __ExPanel(0.,ph21,pw210,1.,1,'MODEL',0.,-ph11) if M: __ModelPanel() else: __RemoveModelPanel() A = __ExPanel(1.-pw210,ph21,1.,1.,3,'ANIM',0.,-ph11) if A: __AnimPanel() else: __RemoveAnimPanel() DCX1,DCX2=pw210 if M else 0.,1.-pw210 if A else 1. D = __ExPanel(pw211 if M else 0.,ph21,1.-pw211 if A else 1.,ph150,2,'DSPL',(0. if M else pw105)+(0. if A else -pw105)) if D: __DisplayPanel(DCX1,DCX2) else: __RemoveDisplayPanel() C = __ExPanel(pw211 if M else 0.,1.-ph150,1.-pw211 if A else 1.,1.,0,'CTRL',(0. if M else pw105)+(0. if A else -pw105)) if C: __ControlPanel(DCX1,DCX2) else: __RemoveControlPanel() __GL.glDisable(__GL.GL_BLEND) #axis #TODO: use a GL display list for this: __GL.glLineWidth(1.0) __GL.glPushMatrix() __GL.glTranslatef(pw228 if M else pw17,1-(ph167 if C else ph17),0) __GL.glScalef(pw600,ph600,1) __GL.glMultMatrixf(RotMatrix) __GL.glColor3f(1.0,0.0,0.0) __GL.glBegin(__GL.GL_LINES); __GL.glVertex3f(0.0,0.0,0.0); __GL.glVertex3f(0.02,0.0,0.0); __GL.glEnd() #X __GL.glTranslatef(0.0145,0.0,0.0); __GL.glRotatef(90, 0.0, 1.0, 0.0) #__GLUT.glutSolidCone(0.003, 0.011, 8, 1) __GL.glRotatef(-90, 0.0, 1.0, 0.0); __GL.glTranslatef(-0.0145,0.0,0.0) __GL.glColor3f(0.0,1.0,0.0) __GL.glBegin(__GL.GL_LINES); __GL.glVertex3f(0.0,0.0,0.0); __GL.glVertex3f(0.0,-0.02,0.0); __GL.glEnd() #Y __GL.glTranslatef(0.0,-0.0145,0.0); __GL.glRotatef(90, 1.0, 0.0, 0.0) #__GLUT.glutSolidCone(0.003, 0.011, 8, 1) __GL.glRotatef(-90, 1.0, 0.0, 0.0); __GL.glTranslatef(0.0,0.0145,0.0) __GL.glColor3f(0.0,0.0,1.0) __GL.glBegin(__GL.GL_LINES); __GL.glVertex3f(0.0,0.0,0.0); __GL.glVertex3f(0.0,0.0,0.02); __GL.glEnd() #Z __GL.glTranslatef(0.0,0.0,0.0145) #__GLUT.glutSolidCone(0.003, 0.011, 8, 1) __GL.glTranslatef(0.0,0.0,-0.0145) __GL.glColor3f(0.5,0.5,0.5) ; #__GLUT.glutSolidSphere(0.003, 8, 4) __GL.glPopMatrix() global __TextureCache __GL.glEnable(__GL.GL_BLEND) for lid in layer: l=layer[lid] __GL.glEnable(__GL.GL_DEPTH_TEST) sl=len(l.stack)-1 #print 'layer[%i]:'%lid #print '%i stack layers:'%(sl+1) for sid in l.stack: #the hash order shold already order as 0+ (0 being the BG, [-1] the FG) #reverse the order (draw FG first at highest point then draw BG(s) behind FG) n=sl-sid; d=(n)*.01 sprimitives=l.stack[n].primitives #print ' stack[%i] - %i primitives:'%(n,len(sprimitives)) for spname in sprimitives: #print ' "%s"'%spname p=sprimitives[spname] #localize the primitive for easy reference __GL.glColor4f(p.r,p.g,p.b,p.a) if p.isTri: __GL.glBegin(__GL.GL_TRIANGLES); __GL.glVertex3fv(p.v1+[d]); __GL.glVertex3fv(p.v2+[d]); __GL.glVertex3fv(p.v3+[d]); __GL.glEnd() else: __GL.glBegin(__GL.GL_QUADS); __GL.glVertex3fv(p.v1+[d]); __GL.glVertex3fv(p.v2+[d]); __GL.glVertex3fv(p.v3+[d]); __GL.glVertex3fv(p.v4+[d]); __GL.glEnd() __GL.glDisable(__GL.GL_DEPTH_TEST) #print '%i ovarlay/font layers:'%len(l.overlay) for oid in l.overlay: oprimitives=l.overlay[oid].primitives #print ' overlay[%i] - %i primitives:'%(oid,len(oprimitives)) for opname in oprimitives: #print ' "%s"'%opname p=oprimitives[opname] #localize the primitive for easy reference __GL.glColor4f(p.r,p.g,p.b,p.a) if p.isTri: __GL.glBegin(__GL.GL_TRIANGLES); __GL.glVertex2fv(p.v1); __GL.glVertex2fv(p.v2); __GL.glVertex2fv(p.v3); __GL.glEnd() else: __GL.glBegin(__GL.GL_QUADS); __GL.glVertex2fv(p.v1); __GL.glVertex2fv(p.v2); __GL.glVertex2fv(p.v3); __GL.glVertex2fv(p.v4); __GL.glEnd() #TODO: set up an array of globally indexed named display lists for each character of a specified font size #to achieve this, we want to collect the font, the size, and the text for every font instance in the layers, #test if those fonts exist as a series of named indecies for display list dictionaries, #and create them if not #font=fonts['name']. """ __GL.glEnable(__GL.GL_TEXTURE_2D) strings=l.font[oid].strings #print ' font[%i] - %i strings:'%(oid,len(strings)) for sname in strings: #print ' "%s"'%sname s=strings[sname] #localize _TCName = '%s%s'%(sname,s.text) if _TCName not in __TextureCache: #generate a new GL texture object #__GL.glActiveTexture(__GL.GL_TEXTURE0) if s.enabled: __GL.glColor4f(s.r,s.g,s.b,s.a) ''' __GL.glRasterPos2f(s.x,s.y) __GL.glDrawPixels(s.w,s.h,__GL.GL_ALPHA,__GL.GL_UNSIGNED_BYTE,s.tid) ''' __GL.glBindTexture( __GL.GL_TEXTURE_2D, s.tid ) __GL.glBegin(__GL.GL_QUADS) __GL.glTexCoord2f(0.0,0.0); __GL.glVertex2f(s.x,s.y) __GL.glTexCoord2f(1.0,0.0); __GL.glVertex2f(s.X,s.y) __GL.glTexCoord2f(1.0,1.0); __GL.glVertex2f(s.X,s.Y) __GL.glTexCoord2f(0.0,1.0); __GL.glVertex2f(s.x,s.Y) __GL.glEnd() #''' else: pass __GL.glDisable(__GL.GL_TEXTURE_2D) """ #raw_input() #for debugging: (draw the active HitDefs) global showHitDefs,Widgets if showHitDefs: __GL.glDisable(__GL.GL_BLEND) for wname in Widgets: W=Widgets[wname] HD=W.hitdef if HD.enabled: __GL.glLineWidth(1.5) x=HD.x; y=HD.y; X=HD.X; Y=HD.Y __GL.glBegin(__GL.GL_LINE_LOOP) __GL.glColor3f(1 if W.event.hasFocus else 0,1,0) #hitdef will be yellow if focused on __GL.glVertex2f(x,y); __GL.glVertex2f(X,y) __GL.glVertex2f(X,Y); __GL.glVertex2f(x,Y) __GL.glEnd() __GL.glLineWidth(1.0) global doFrameCheck if doFrameCheck: __FrameCheck(); doFrameCheck=False def __initGUI(): __pyg.font.init() #__GL.glTexEnvf( __GL.GL_TEXTURE_ENV, __GL.GL_TEXTURE_ENV_MODE, __GL.GL_MODULATE )
{ "repo_name": "Universal-Model-Converter/UMC3.0a", "path": "dev tests and files/data (scrapped dev5 attempt)/GUI_new.py", "copies": "1", "size": "54979", "license": "mit", "hash": 4800527526848586000, "line_mean": 37.9376770538, "line_max": 175, "alpha_frac": 0.6085778206, "autogenerated": false, "ratio": 2.9665461609021744, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8879161256241567, "avg_score": 0.039192545052121525, "num_lines": 1412 }
""" 1: Object-Oriented Programming Some examples of Object-Oriented programming with Python thomas moll 2015 """ class Vehicle(object): number_of_wheels = None def __init__(self, name): self.name = name def __str__(self): return 'Type: '+str(self.__class__)+' Name: '+self.name @property def name(self): return self._name @name.setter def name(self, new_value): if len(new_value) > 3: self._name = new_value else: raise ValueError("Name length must be greater than 5 characters") def vroom(self): raise NotImplementedError("A generic vehicle doesn't make a sound!") class Car(Vehicle): def __init__(self, name): super(Car, self).__init__(name) self.number_of_wheels = 4 def vroom(self): return 'Put Put Put' class Truck(Vehicle): def __init__(self,name): super(Truck, self).__init__(name) self.number_of_wheels = 18 def vroom(self): return 'Vroooooom'
{ "repo_name": "ston380/Data-Structure-Zoo", "path": "0-Object-Oriented Programming/objects.py", "copies": "15", "size": "1090", "license": "mit", "hash": 8236681032901480000, "line_mean": 21.6956521739, "line_max": 77, "alpha_frac": 0.5587155963, "autogenerated": false, "ratio": 3.797909407665505, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
#~ 1) On line 50 set the server name, at line 54 set hostname, institution, sharedsecret and id (from user management / shared secret) #~ 2) From cmd c:\python25\python.exe impersonate_generic.py (or F5 from SciTE) #~ - this will set up a webserver on your machine on port 8000 for the impersonation #~ 3) Start up a browser session and go to: http://localhost:8000/ #~ 4) You should get a short HTML page with a box and a button. Type the username in the box and press the button. #~ 5) A hyperlink should appear saying "log in as <username>". Click it. #~ 6) When you have finished, just close the DOS session and the impersonatron will go away... import md5 from binascii import b2a_base64 from urllib import urlencode import time import BaseHTTPServer import sys import cgi from tleclient30 import createSSOToken def md5this (s): m = md5.new () m.update (s) return m.digest () class OurHandler (BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.send_response (200) self.send_header("Content-type", "text/html") self.end_headers () try: # redirect stdout to client stdout = sys.stdout sys.stdout = self.wfile self.makepage () finally: sys.stdout = stdout # restore def makepage(self): idx = self.path.find ('?') username = None if idx > 0: qs = self.path [idx + 1:] vals = cgi.parse_qs (qs) if vals.has_key ('username'): usernames = vals ['username'] if len (usernames): username = usernames [0] print "<html>" print "<body>" print "<form action='/' method='get'>" print "Username for <server>: <input type='text' name='username' />" print "<input type='Submit' value='impersonate' />" print "</form>" if username: print '<a href="%s" target="_blank">Log in as %s</a>' % ('<host>/<institution>/access/Tasks.jsp?%s' % urlencode ({'token': createSSOToken (username, '<sharedsecret>', '<id>')}), username) print "</body>" print "</html>" httpd = BaseHTTPServer.HTTPServer(('', 8000), OurHandler) httpd.serve_forever()
{ "repo_name": "equella/Equella", "path": "Source/Tools/ImportLibraries/Python/impersonate_generic.py", "copies": "1", "size": "2020", "license": "apache-2.0", "hash": -8269958338410626000, "line_mean": 32.6666666667, "line_max": 190, "alpha_frac": 0.6846534653, "autogenerated": false, "ratio": 3.2845528455284554, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4469206310828456, "avg_score": null, "num_lines": null }
# 1 = only crash errors # 2 = error + warning # 3 = All output error_level = 3 repository = r"C:\tmp\VBad" #functions available : onClose, onOpen auto_function_macro = "onOpen" trigger_close_test_value="True" trigger_close_test_name = "toto" #methods available: variables key_hiding_method = "variable" #doc_variable options add_fake_keys = 1 small_keys = 4 big_keys = 3 #options ##use these vulnerability : http://seclists.org/fulldisclosure/2017/Mar/90 ##Replace module name that contains effective payload with 0X0A 0X0D. The module becomes invisible from Developper Tools making analyse more complicated :) delete_module_name = 1 #encryption available : xor encryption_type = "xor" encryption_key_length = 50000 #Max is 65280 for Document.Variable method #Regex variable_name_ex = "toto" regex_rand_var = '\[rdm::([0-9]+)\](\w*)' #regex that select the name of the variable, after the delimiter and the length regex_rand_del = '\[rdm::[0-9]+\]' #regex should select only the delimiter regex_defaut_string = '"((?:""|[^"])*)"' #Regex selecting all strings in double quotes (including two consecutives double quotes) regex_exclude_string_del = '\[!!\]' #The exclusion is to avoid vba string that could finish with exclude characters. exclude_mark = '[!!]' regex_string_to_hide = '\[var::(\w*)\]' regex_string_to_hide_find = '\[var::'+variable_name_ex+'\]' #Office informations template_file = repository+r"\Example\Template\template.doc" #Path to the template file used for generate malicious files (To be modified) filename_list = repository+r"\Example\Lists\filename_list.txt" #Path to the list that contains the filename of the malicious files that will be generated (To be modified) #saving informations path_gen_files = repository+r"\Example\Results" #Path were results will be saved (To be modified) #Malicious VBS Information: #All data you want to encrypt and include in your doc original_vba_file = repository+r"\Example\Orignal_VBA\original_vba_prepared.vbs" #Path the prepared VBA files (To be modified) trigger_function_name = "Test" #Function that you want to auto_trigger (in your original_vba_file) (To be modified) string_to_hide = {"domain_name":"http://www.test.com", "path_to_save":r"C:\tmp\toto"}
{ "repo_name": "Pepitoh/VBad", "path": "const.py", "copies": "1", "size": "2285", "license": "mit", "hash": -8275678165686918000, "line_mean": 41.1132075472, "line_max": 170, "alpha_frac": 0.7207877462, "autogenerated": false, "ratio": 3.2183098591549295, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9342809406146402, "avg_score": 0.01925763984170559, "num_lines": 53 }
#1 origional size images, limited to 100 images per page #1.1 Added links to the bottom of the page to progress through the galleries #1.2 Resized the images to 200x200 and increased the images to 400 per page #2 Added logic to chew through the XML files. The program will now go through all the g.sitemap.xxx.xml files. # This makes it so it searches the entire server of xml filesfor images. #2.1 Added additional logic so the system will read through all the files on each server. Application starts with 001 on s0001 # continues through to 999 on s9999 #2.2 Added condition to allow you to choose between full server crawl and stop when empty XML file is found. import urllib import urllib2 runP = "true" moreS = "true" moreF = "true" numPix = 1 fileNum = 0 xplace1 = 0 xplace2 = 0 xplace3 = 1 sPlace1 = 0 sPlace2 = 0 sPlace3 = 0 sPlace4 = 1 response = urllib2.urlopen("http://s"+str(sPlace1)+str(sPlace2)+str(sPlace3)+str(sPlace4)+".photobucket.com/g.sitemap."+str(xplace1)+str(xplace2)+str(xplace3)+".xml") http = response.read() print "Starting at " + "http://s"+str(sPlace1)+str(sPlace2)+str(sPlace3)+str(sPlace4)+".photobucket.com/g.sitemap."+str(xplace1)+str(xplace2)+str(xplace3)+".xml" ################################################################### # Set to 1 to scan all XML files before going to the next server # # Set to 2 to stop scanning when a blank XML file is found # ################################################################### sScan = 2 ################################################################### ################################################################### myOutputFile = open("PBThumb.html", "wb") #This writes the file as a recognizable HTML file. Load the files in your web browser to view the thumbs. openingLines = ['\n<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"', '\n "http://www.w3.org/TR/html4/loose.dtd">', '\n<html lang="en">', '\n', '\n<head>', '\n<meta http-equiv="content-type" content="text/html; charset=utf-8">', '\n<title>Photobucket Thumbs</title>', '\n</head>', '\n', '\n<body>'] closingLines =['\n</body>', '\n</html>'] myOutputFile.writelines(openingLines) sPix = 1 #The system will continue running until a blank XML file is found or a server error is encountered. No error handling has been included in this to prevent a perpetual loop/ while moreS == "true": while moreF == "true": while runP == "true": if numPix >= 400: numPix = 0 fileNum = fileNum + 1 myOutputFile.writelines('\n<a href="PBThumb'+str(fileNum)+'.html">Next Page</a>') myOutputFile.writelines(closingLines) myOutputFile.close() myOutputFile = open("PBThumb"+str(fileNum)+".html", "wb") myOutputFile.writelines(openingLines) if http.find('image:loc') <= 0: runP = "false" startP = http.find('image:loc') + 10 http = http[startP:] endP = http.find('image:loc') - 2 hName = http[:endP] if hName != "": PBLink = '\n<a href="'+hName+'"><img src="'+hName+'" height="200" width="200"></a>' myOutputFile.writelines(PBLink) sPix = sPix + 1 numPix = numPix + 1 http = http[endP+12:] #The following logic increments the XML files. if xplace3 == 9: xplace3 = 0 if xplace2 == 9: xplace2 = 0 if xplace1 == 9: moreF = "false" else: xplace1 = xplace1 + 1 else: xplace2 = xplace2 + 1 else: xplace3 = xplace3 + 1 if sScan == 2: if sPix == 0: moreF = "false" #This loads the next XML file and lets the user know what file is being loaded. response = urllib2.urlopen("http://s"+str(sPlace1)+str(sPlace2)+str(sPlace3)+str(sPlace4)+".photobucket.com/g.sitemap."+str(xplace1)+str(xplace2)+str(xplace3)+".xml") http = response.read() print sPix sPix = 0 if moreF == "true": print "Moving to " + "http://s"+str(sPlace1)+str(sPlace2)+str(sPlace3)+str(sPlace4)+".photobucket.com/g.sitemap."+str(xplace1)+str(xplace2)+str(xplace3)+".xml" #Resetting the runP variable so the system will processall the files. runP = "true" if sPlace4 == 9: sPlace4 = 0 if sPlace3 == 9: sPlace3 = 0 if sPlace2 == 9: sPlace2 = 0 if sPlace1 == 9: moreS = "false" else: sPlace1 = sPlace1 + 1 else: sPlace2 = sPlace2 + 1 else: sPlace3 = sPlace3 + 1 else: sPlace4 = sPlace4 + 1 xplace1 = 0 xplace2 = 0 xplace3 = 1 moreF = "true" print "Moving to " + "http://s"+str(sPlace1)+str(sPlace2)+str(sPlace3)+str(sPlace4)+".photobucket.com/g.sitemap."+str(xplace1)+str(xplace2)+str(xplace3)+".xml" response = urllib2.urlopen("http://s"+str(sPlace1)+str(sPlace2)+str(sPlace3)+str(sPlace4)+".photobucket.com/g.sitemap."+str(xplace1)+str(xplace2)+str(xplace3)+".xml") http = response.read() myOutputFile.writelines(closingLines) myOutputFile.close() print "Done"
{ "repo_name": "AlecWallace2001/PBPull", "path": "PBPull.py", "copies": "1", "size": "5411", "license": "mit", "hash": 825556795791383200, "line_mean": 43.3524590164, "line_max": 319, "alpha_frac": 0.5634817963, "autogenerated": false, "ratio": 3.4954780361757107, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4558959832475711, "avg_score": null, "num_lines": null }
## 1. Overview ## f = open("dictionary.txt", "r") vocabulary = f.read() print(vocabulary) ## 2. Tokenizing the Vocabulary ## vocabulary = open("dictionary.txt", "r").read() tokenized_vocabulary = vocabulary.split(" ") print(tokenized_vocabulary[0:5]) ## 3. Replacing Special Characters ## f = open("story.txt", 'r') story_string = f.read() print(story_string) story_string = story_string.replace(".","") story_string = story_string.replace(",","") story_string = story_string.replace("'", "") story_string = story_string.replace(";", "") story_string = story_string.replace("\n", "") print(story_string) ## 5. Practice: Creating a Function that Cleans Text ## f = open("story.txt", 'r') story_string = f.read() def clean_text(text_string): cleaned_string = text_string.replace(".","") cleaned_story = clean_text(story_string) # Solution code. def clean_text(text_string): cleaned_string = text_string.replace(".","") cleaned_string = cleaned_string.replace(",","") cleaned_string = cleaned_string.replace("'", "") cleaned_string = cleaned_string.replace(";", "") cleaned_string = cleaned_string.replace("\n", "") return(cleaned_string) cleaned_story = clean_text(story_string) ## 6. Changing Word Case ## def clean_text(text_string): cleaned_string = text_string.replace(",","") cleaned_string = cleaned_string.replace(".","") cleaned_string = cleaned_string.replace("'", "") cleaned_string = cleaned_string.replace(";", "") cleaned_string = cleaned_string.replace("\n", "") return(cleaned_string) cleaned_story = clean_text(story_string) def clean_text(text_string): cleaned_string = text_string.replace(",","") cleaned_string = cleaned_string.replace(".","") cleaned_string = cleaned_string.replace("'", "") cleaned_string = cleaned_string.replace(";", "") cleaned_string = cleaned_string.replace("\n", "") cleaned_string = cleaned_string.lower() return(cleaned_string) cleaned_story = clean_text(story_string) ## 7. Multiple Arguments ## f = open("story.txt", 'r') story_string = f.read() clean_chars = [",", ".", "'", ";", "\n"] # Previous code for clean_text(). def clean_text(text_string): cleaned_string = text_string.replace(",","") cleaned_string = cleaned_string.replace(".","") cleaned_string = cleaned_string.replace("'", "") cleaned_string = cleaned_string.replace(";", "") cleaned_string = cleaned_string.replace("\n", "") cleaned_string = cleaned_string.lower() return(cleaned_string) cleaned_story = "" def clean_text(text_string, special_characters): cleaned_string = text_string for string in special_characters: cleaned_string = cleaned_string.replace(string, "") cleaned_string = cleaned_string.lower() return(cleaned_string) cleaned_story = clean_text(story_string, clean_chars) print(cleaned_story) ## 8. Tokenizing the Story ## def clean_text(text_string, special_characters): cleaned_string = text_string for string in special_characters: cleaned_string = cleaned_string.replace(string, "") cleaned_string = cleaned_string.lower() return(cleaned_string) clean_chars = [",", ".", "'", ";", "\n"] cleaned_story = clean_text(story_string, clean_chars) def tokenize(text_string, special_characters): cleaned_story = clean_text(text_string, special_characters) story_tokens = cleaned_story.split(" ") return(story_tokens) tokenized_story = tokenize(story_string, clean_chars) print(tokenized_story[0:10]) ## 9. Finding Misspelled Words ## def clean_text(text_string, special_characters): cleaned_string = text_string for string in special_characters: cleaned_string = cleaned_string.replace(string, "") cleaned_string = cleaned_string.lower() return(cleaned_string) def tokenize(text_string, special_characters): cleaned_story = clean_text(text_string, special_characters) story_tokens = cleaned_story.split(" ") return(story_tokens) misspelled_words = [] clean_chars = [",", ".", "'", ";", "\n"] tokenized_story = tokenize(story_string, clean_chars) tokenized_vocabulary = tokenize(vocabulary, clean_chars) for ts in tokenized_story: if ts not in tokenized_vocabulary: misspelled_words.append(ts) print(misspelled_words)
{ "repo_name": "vipmunot/Data-Analysis-using-Python", "path": "Python Programming Beginner/Introduction to Functions-4.py", "copies": "1", "size": "4282", "license": "mit", "hash": -4019859173405880000, "line_mean": 31.2030075188, "line_max": 63, "alpha_frac": 0.6742176553, "autogenerated": false, "ratio": 3.478472786352559, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4652690441652559, "avg_score": null, "num_lines": null }
# 1. p:camera The first query returns all records that have the term camera in the product title. # 2. r:great The second query return all records that have the term great in the review summary or text. # 3. camera The third query returns all records that have the term camera in one of the fields product title, review summary or review text. # 4. cam% The fourth query returns all records that have a term starting with cam in one of the fields product title, review summary or review text. # 5. r:great cam% The fifth query returns all records that have the term great in the review summary or text and a term starting with cam in one of the fields product title, review summary or review text. # 6. rscore > 4 The sixth query returns all records with a review score greater than 4 # 7. camera rscore < 3 The 7th query is the same as the third query except it returns only those records with a review score less than 3 # 8. pprice < 60 camera The 8th query is the same as the third query except the query only returns those records where price is present and has a value less than 60. Note that there is no index on the price field; this field is checked after retrieving the candidate records using conditions on which indexes are available (e.g. terms). # 9. camera rdate > 2007/06/20 The 9th query returns the records that have the term camera in one of the fields product title, review summary or review text, and the review date is after 2007/06/20. Since there is no index on the review date, this condition is checked after checking the conditions on terms. Also the review date stored in file reviews.txt is in the form of a timestamp, and the date give in the query must be converted to a timestamp before a comparison (e.g. check out the date object in the datetime package for Python). # 10. camera rdate > 2007/06/20 pprice > 20 pprice < 60 Finally the last query returns the same set of results as in the 9th query except the product price must be greater than 20 and less than 60. import re import time from IndexDB import * from rgxHandler import * from datetime import * import operator class Phase3: reviewsDB = None ptermsDB = None rtermsDB = None scoresDB = None rgx = None firstIntersectFlag = False def __init__(self): self.rgx = rgxHandler() def start(self): print("######################################################") print("############# PHASE 3 INITIALIZING QUERY #############") print("######################################################" + '\n') print("######################################################") print("############# REVIEW LOOKUP SYSTEM #############") #print("############# " + "Type 'q!' to quit" + " #############") print("######################################################" + '\n') self.reviewsDB = IndexDB('rw.idx') self.ptermsDB = IndexDB('pt.idx') self.rtermsDB = IndexDB('rt.idx') self.scoresDB = IndexDB('sc.idx') print("Type 'q!' to exit") def main(self): while(1): query = input("Please provide a Query: ") print("") if query == "q!": self.reviewsDB.close() self.ptermsDB.close() self.rtermsDB.close() self.scoresDB.close() exit() parsedQuery = self.queryParser(query) # print(parsedQuery) listOfReviews = self.getReviews(parsedQuery) # print(listOfReviews) self.displayReviews(listOfReviews) def displayReviews(self, listOfReviews): i = 0 for reviewKey in listOfReviews: i += 1 reviewValue = self.reviewsDB.get(reviewKey)[0] #print(reviewValue) print("######################################################") print("################# REVIEW " + str(i) + " #################") print("######################################################" + '\n') reviewValue = self.rgx.putLineTitlesBack(reviewValue) for line in reviewValue: if( "review/time" in line): time = datetime.fromtimestamp(float(line.split(":")[1].strip("\n").strip())) print("review/time: " + time.strftime("%b %d %Y")+ "\n") else: print(line, end='') print('\n') def getReviews(self, parsedQuery): """ Using the parsedQuery data, intersects the conditional filters amongs the reviews. Until a filtered list of results is generated. >>> p3 = Phase3() >>> p3.start() ###################################################### ############# PHASE 3 INITIALIZING QUERY ############# ###################################################### <BLANKLINE> ###################################################### ############# REVIEW LOOKUP SYSTEM ############# ###################################################### <BLANKLINE> Type 'q!' to exit >>> parsedQuery = ([], [], [], []) >>> p3.getReviews(parsedQuery) [] >>> parsedQuery = ([], [], [('r', 'ago')], []) >>> p3.getReviews(parsedQuery) ['9'] >>> parsedQuery = (['ago'], [], [], []) >>> p3.getReviews(parsedQuery) ['9'] >>> parsedQuery = (['again'], [], [], []) >>> p3.getReviews(parsedQuery) ['8', '10'] >>> parsedQuery = (['again', 'used'], [], [], []) >>> p3.getReviews(parsedQuery) ['10'] >>> parsedQuery = ([], ['ag'], [], []) >>> p3.getReviews(parsedQuery) ['8', '9', '10'] >>> parsedQuery = (['again'], ['ag'], [], []) >>> p3.getReviews(parsedQuery) ['8', '10'] >>> parsedQuery = ([], [], [], [('rdate', '<', '2000/01/01')]) >>> p3.getReviews(parsedQuery) ['4', '5'] >>> parsedQuery = ([], [], [], [('rdate', '<', '2000/01/01'), ('pprice', '<', '17')]) >>> p3.getReviews(parsedQuery) ['5'] >>> parsedQuery = (['cross'], [], [], []) >>> p3.getReviews(parsedQuery) ['5', '7', '8', '9', '10'] >>> parsedQuery = ([], [], [('r', 'cross')], []) >>> p3.getReviews(parsedQuery) ['5', '7', '8', '10'] >>> parsedQuery = ([], [], [('p', 'cross')], []) >>> p3.getReviews(parsedQuery) ['7', '8', '9', '10'] >>> parsedQuery = ([], ['not'], [], []) >>> p3.getReviews(parsedQuery) ['1', '2', '8', '9'] >>> parsedQuery = ([], ['not'], [('r', 'cross')], []) >>> p3.getReviews(parsedQuery) ['8'] >>> parsedQuery = ([], [], [], [('rscore', '<', '5')]) >>> p3.getReviews(parsedQuery) ['1', '3', '4'] >>> parsedQuery = ([], [], [], [('rscore', '>', '4')]) >>> p3.getReviews(parsedQuery) ['2', '5', '6', '7', '8', '9', '10'] >>> parsedQuery = (['find'], [], [], [('rscore', '<', '5')]) >>> p3.getReviews(parsedQuery) ['1', '4'] >>> parsedQuery = ([], [], [], [('pprice', '<', '16')]) >>> p3.getReviews(parsedQuery) ['5', '6'] >>> parsedQuery = (['old'], [], [], [('pprice', '<', '16')]) >>> p3.getReviews(parsedQuery) ['6'] >>> parsedQuery = ([], [], [], [('rdate', '<', '2000/01/01')]) >>> p3.getReviews(parsedQuery) ['4', '5'] >>> parsedQuery = (['find'], [], [], [('rdate', '<', '2000/01/01')]) >>> p3.getReviews(parsedQuery) ['4'] >>> parsedQuery = ([], [], [], [('rdate', '>', '2000/01/01')]) >>> p3.getReviews(parsedQuery) ['1', '2', '3', '6', '7', '8', '9', '10'] >>> parsedQuery = ([], [], [], [('rdate', '>', '2009/01/01'), ('pprice', '>', '16'), ('pprice', '<', '18')]) >>> p3.getReviews(parsedQuery) ['2'] >>> parsedQuery = (['shazam'], [], [], [('rdate', '>', '2009/01/01'), ('pprice', '>', '16'), ('pprice', '<', '18')]) >>> p3.getReviews(parsedQuery) [] """ self.firstIntersectFlag = False reviewList = [] tmpList = [] #Select by selections, selector = (selector, searchTerm) for entry in parsedQuery[2]: selector = entry[0] term = entry[1] if(selector == "r"): subList = self.rtermsDB.get(term) for i in subList: tmpList.append(i) elif(selector == "p"): subList = self.ptermsDB.get(term) for i in subList: tmpList.append(i) reviewList = self.ourIntersect(reviewList, tmpList) tmpList = [] #Select by words, word = (searchTerm) for entry in parsedQuery[0]: subList = self.rtermsDB.get(entry) for i in subList: tmpList.append(i) subList = self.ptermsDB.get(entry) for i in subList: tmpList.append(i) reviewList = self.ourIntersect(reviewList, tmpList) tmpList = [] #Select by wilds, wild = (searchTerm) for entry in parsedQuery[1]: subList = self.rtermsDB.getWild(entry) for i in subList: tmpList.append(i) subList = self.ptermsDB.getWild(entry) for i in subList: tmpList.append(i) reviewList = self.ourIntersect(reviewList, tmpList) tmpList = [] #Select by comparator, comparator = (comparator, operator, value) #pprice < 20 #rdate > 2007/06/20 #rscore < 3 #product/price: unknown #review/score: 5.0 #review/time: 1075939200 for entry in parsedQuery[3]: comparator = entry[0] oper = entry[1] value = entry[2] ops = {"<": operator.lt, ">": operator.gt} if(comparator == "rdate"): comparator = "rtime" year,month,day = value.split("/") try: value = datetime(int(year), int(month), int(day)) except: print("Invalid Date Provided. No Results Found.") return [] else: value = value + ".0" keys = self.reviewsDB.getAllReviewKeys() for key in keys: item = self.rgx.putLineTitlesBack( self.reviewsDB.get(key)[0] ) itemPrice = item[2].split(":")[1].strip("\n").strip() itemScore = item[6].split(":")[1].strip("\n").strip() itemDate = datetime.fromtimestamp( float(item[7].split(":")[1].strip("\n").strip() )) # print(itemPrice) # print(itemScore) # print(itemDate) # print("") comp_to_val = {"pprice": itemPrice, "rscore": itemScore, "rtime": itemDate } if ops[oper](comp_to_val[comparator], value) : tmpList.append(key) reviewList = self.ourIntersect(reviewList, tmpList) tmpList = [] # print(reviewList) return sorted(reviewList, key=float) def ourIntersect(self, b1, b2): if(not self.firstIntersectFlag): self.firstIntersectFlag = True return list(set(b2)) else: return list(set(b1).intersection(b2)) def queryParser(self, query): """ Parser returns tuples containing 4 lists containng tuples. ([words], [wilds], [selectors], [comparators]) word = (searchTerm) wild = (searchTerm) selector = (selector, searchTerm) comparator = (comparator, operator, value) >>> p3 = Phase3() >>> p3.queryParser("") ([], [], [], []) >>> result = p3.queryParser("P:caMeRa") >>> result[2] [('p', 'camera')] >>> result = p3.queryParser("r:grEaT") >>> result[2] [('r', 'great')] >>> result =p3.queryParser("cAmeRa") >>> result[0] ['camera'] >>> result = p3.queryParser("cam%") >>> result[1] ['cam'] >>> result = p3.queryParser("r:great cam%") >>> result[1] ['cam'] >>> result[2] [('r', 'great')] >>> result = p3.queryParser("rscore > 4") >>> result[3] == [('rscore', '>', '4')] True >>> result = p3.queryParser("camera rscore < 3") >>> result[0] ['camera'] >>> result[3] == [('rscore', '<', '3')] True >>> result = p3.queryParser("pprice < 60 camera") >>> result[0] ['camera'] >>> result[3] == [('pprice', '<', '60')] True >>> result = p3.queryParser("camera rdate > 2007/06/20") >>> result[0] ['camera'] >>> result[3] == [('rdate', '>', '2007/06/20')] True >>> result = p3.queryParser("camera rdate > 2007/06/20 pprice > 20 pprice < 60") >>> result[0] ['camera'] >>> result[3] == [('rdate', '>', '2007/06/20'), ('pprice', '>', '20'), ('pprice', '<', '60')] True """ query = query.strip().lower().rstrip('\r\n') searchTerms = [] #(searchTerm) wildCardTerms = [] #(searchTerm) selectors = [] #(selector, searchTerm) comparators = [] #(comparator, operator, value) selector = re.compile(r"(r:|p:)[a-z]*") wild = re.compile(r"[a-z]*%") comparator = re.compile(r"\w*\s(<|>)\s[\w/]*") word = re.compile(r"[a-z]+") while(query != ""): # time.sleep(3) # print("looping query: " + query) query.strip().rstrip('\r\n') if(comparator.search(query)): found = comparator.search(query).group(0) query = query.replace(found, "") if(">" in found): comparators.append( (found.split(">")[0].strip(),">",found.split(">")[1].strip()) ) else: comparators.append( (found.split("<")[0].strip(),"<",found.split("<")[1].strip()) ) continue elif (selector.match(query)): # print("Selector found") found = selector.search(query).group(0) query = query.replace(found, "") selectors.append((found.split(":")[0],found.split(":")[1])) continue elif (wild.search(query)): # print("wild found") found = wild.search(query).group(0) query = query.replace(found, "") wildCardTerms.append(found.strip("%")) continue elif (word.search(query)): # print("Word found") found = word.search(query).group(0) query = query.replace(found, "") searchTerms.append(found) continue else: break return (searchTerms,wildCardTerms,selectors,comparators) if __name__ == "__main__": import doctest doctest.testmod() p3 = Phase3() p3.start() p3.main()
{ "repo_name": "quentinlautischer/291MiniProject2", "path": "src/phase3.py", "copies": "1", "size": "15532", "license": "apache-2.0", "hash": -8887391866331831000, "line_mean": 34.3, "line_max": 541, "alpha_frac": 0.4709631728, "autogenerated": false, "ratio": 3.997940797940798, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.994679236610855, "avg_score": 0.004422320926449641, "num_lines": 440 }
"""1.Phase""" from sympy import * init_printing() z, x0, x1, x2, x3, x4, x5, x6, x7 = symbols('z, x0, x1, x2, x3, x4, x5, x6, x7') B = [x3, x4, x5, x6, x7] N = [x0, x1, x2] rows = [Eq(x3, -12 + 2 * x1 + 1 * x2 + x0), Eq(x4, -12 + x1 + 2 * x2 + x0), Eq(x5, -10 + x1 + x2 + x0), Eq(x6, 60 - 3 * x1 - 4 * x2 + x0), Eq(x7, 12 - x1 + x0)] ziel = Eq(z, - x0) # ------------------------------------------------------------------------------- eintretende = x0 for i in range(10): # eintretende Variable finden # auswaehlen nach dem Teknik in der Vorlesung (d.h. var mit grosstem Koeffizeint) if i != 0: # nicht in erstem Durchlauf (da hier unzulaessig) eintretende = None max_eintretende = -oo for var, coeff in ziel.rhs.as_coefficients_dict().items(): # 1 is the first coeff i.e. the value of the ziel function if var != 1 and coeff > 0 and coeff > max_eintretende: max_eintretende = coeff eintretende = var # if no positiv costs => optimal if eintretende == None: break # verlassende Variable finden verlassende = None min_wert = +oo min_row = None if i == 0: # einfach definierne da im ersten Durchlauf Dich ist unzulaessig # verlassende = min([row.rhs.as_coefficients_dict()[1] for row in rows]) verlassende = x3 min_row = rows[0] else: for row in rows: if row.has(eintretende): new_row = row for nbv in N: if nbv != eintretende: new_row = new_row.subs(nbv, 0) wert = solve(new_row.rhs >= 0).as_set().right if wert < min_wert: min_wert = wert min_row = row verlassende = row.lhs # die Formlen umsetzen und rows updaten new_formel = Eq(eintretende, solve(min_row, eintretende)[0]) new_rows = [new_formel] for row in rows: if row.lhs != verlassende: new_rows.append(Eq(row.lhs, row.rhs.subs(eintretende, new_formel.rhs))) rows = new_rows # new ziel ziel = Eq(z, ziel.rhs.subs(eintretende, new_formel.rhs)) pprint(latex(ziel)) # update B, N B.remove(verlassende); B.append(eintretende) N.remove(eintretende); N.append(verlassende)
{ "repo_name": "mazenbesher/simplex", "path": "sympy_version/specific/blatt4_aufgabe2_hilfsproblem.py", "copies": "1", "size": "2412", "license": "mit", "hash": -7098804157126376000, "line_mean": 32.0410958904, "line_max": 85, "alpha_frac": 0.5182421227, "autogenerated": false, "ratio": 2.827667057444314, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8823550546858043, "avg_score": 0.004471726657254262, "num_lines": 73 }
"""1. Police department uploads the video to S3 bucket for incoming videos 2. As video are saved in the bucket a threaded script creates an EC2 instance per item in bucket 3. The threaded script sends a command over SSH with the argument being the key name of the video on the S3 bucket 4. The called script then saves the video locally, processes it, saves it in the S3 bucket for finished videos, and halts/terminates itself 5. A threaded script uploads processed videos to endpoint such as Youtube as the processed videos are saved 6. The threaded script generates a series of images every 30 seconds of the video""" # Load our settings.json file which contains AWS keys, bucket names, key_name, security_group_id import json with open('settings.json') as settings_file: settings = json.load(settings_file) from boto.s3.connection import S3Connection s3conn = S3Connection(settings['aws_access_key_id'], settings['aws_secret_access_key']) incoming_bucket = s3conn.get_bucket(settings['incoming_bucket']) import boto.ec2 ec2conn = boto.ec2.connect_to_region(settings['region'], aws_access_key_id=settings['aws_access_key_id'], aws_secret_access_key=settings['aws_secret_access_key']) import time import os import os.path if not os.path.isfile('videos_already_processed.txt'): os.system('touch videos_already_processed.txt') import time while True: import json # Allows one to change the settings without restarting the script with open('settings.json') as settings_file: settings = json.load(settings_file) bucket_items = sorted(incoming_bucket.list(), reverse=True) print 'Got bucket items' for key in bucket_items: if key.name.endswith('.zip'): f = open('videos_already_processed.txt', 'r') files = f.read().split('\n') f.close() if not key.name in files: with open("videos_already_processed.txt", "a") as myfile: myfile.write(key.name+'\n') print 'zip' print key.name os.system('sudo unzip -j -o "/mnt/s3/%s" -d /mnt/s3/' % (key.name)) os.system('sudo rm "/mnt/s3/%s"' % (key.name)) elif key.name.endswith('.mp4') or key.name.lower().endswith('.mpg') or key.name.lower().endswith('.mov'): print key.name f = open('videos_already_processed.txt', 'r') files = f.read().split('\n') f.close() if not key.name in files: with open("videos_already_processed.txt", "a") as myfile: myfile.write(key.name+'\n') print "processing" os.system('python process_video.py "%s" False' % (key.name)) time.sleep(60)
{ "repo_name": "policevideorequests/policevideopublisher", "path": "run_single_instance_strategy.py", "copies": "1", "size": "2756", "license": "bsd-3-clause", "hash": 1226418485367766000, "line_mean": 52, "line_max": 162, "alpha_frac": 0.6509433962, "autogenerated": false, "ratio": 3.7909215955983493, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4941864991798349, "avg_score": null, "num_lines": null }
## 1. Probability basics ## # Print the first two rows of the data. print(flags[:2]) most_bars_country = flags['name'][flags['bars'].idxmax()] highest_population_country = flags['name'][flags['population'].idxmax()] ## 2. Calculating probability ## total_countries = flags.shape[0] orange_probability = len(flags[flags["orange"] == 1])/total_countries stripe_probability = len(flags[flags["stripes"] > 1])/total_countries ## 3. Conjunctive probabilities ## five_heads = .5 ** 5 ten_heads = 0.5 ** 10 hundred_heads = 0.5 ** 100 ## 4. Dependent probabilities ## # Remember that whether a flag has red in it or not is in the `red` column. total = len(flags) red = len(flags[flags['red']==1]) one_red = red/total two_red = one_red * ((red-1)/(total - 1)) three_red = two_red * ((red-2)/(total - 2)) ## 5. Disjunctive probability ## start = 1 end = 18000 def count_evenly_divisible(start, end, div): divisible = 0 for i in range(start, end+1): if (i % div) == 0: divisible += 1 return divisible hundred_prob = count_evenly_divisible(start, end, 100) / end seventy_prob = count_evenly_divisible(start, end, 70) / end ## 6. Disjunctive dependent probabilities ## stripes_or_bars = None red_or_orange = None red = flags[flags["red"] == 1].shape[0] / flags.shape[0] orange = flags[flags["orange"] == 1].shape[0] / flags.shape[0] red_and_orange = flags[(flags["red"] == 1) & (flags["orange"] == 1)].shape[0] / flags.shape[0] red_or_orange = red + orange - red_and_orange stripes = flags[flags["stripes"] > 0].shape[0] / flags.shape[0] bars = flags[flags["bars"] > 0].shape[0] / flags.shape[0] stripes_and_bars = flags[(flags["stripes"] > 0) & (flags["bars"] > 0)].shape[0] / flags.shape[0] stripes_or_bars = stripes + bars - stripes_and_bars ## 7. Disjunctive probabilities with multiple conditions ## heads_or = None all_three_tails = (1/2 * 1/2 * 1/2) heads_or = 1 - all_three_tails
{ "repo_name": "vipmunot/Data-Analysis-using-Python", "path": "Probability Statistics Intermediate/Introduction to probability-48.py", "copies": "1", "size": "1924", "license": "mit", "hash": -3860584104712697000, "line_mean": 29.078125, "line_max": 96, "alpha_frac": 0.6548856549, "autogenerated": false, "ratio": 2.8716417910447762, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4026527445944776, "avg_score": null, "num_lines": null }
#1. Put strings into a list, then use ' '.join(strings) # to concate all strings strings = ["Hello", "World", "You", "!"] name = ' '.join(strings) print name #2. Always use an object's capabilities instead of restrained to its type. #3. Use if not x: x = 10 if not x: print name #4. Use string.function() if name.startswith("Hello"): print name #5, Use try, catch schema """ try: return int(name) except(TypeError, ValueError, overflowError): return None """ #6. Docstrings and Comments # Docstring, How to use the code; Comments: why and how code works? #Swap value: a = 10 b = 9 b, a = a, b #_ stores the last printed expression, for console usage only colors = ['red', 'blue', 'green', 'yellow'] print 'Choose', ', '.join(colors[:-1]), 'or', colors[-1] result = "Choose " + ', '.join(colors[:-1]) + "or " + colors[-1] def fn(color): return color + "10" result = ''.join(fn(i) for i in colors) print result #7, Build dictories from two lists: given = ['John', 'Eric', 'Terry', 'Michael'] family = ['Cleese', 'Idel', 'Gilliam', 'Palin'] pythons = dict(zip(given, family)) print pythons #10, List comprehensions new_list = [fn(item) for item in a_list if condition(item)] total = sum([num*num for num in range(1, 101)]) """Module Docstring""" # imports # constants # exception classes # interface functions # classes # internal functions & classes
{ "repo_name": "martinggww/lucasenlights", "path": "MachineLearning/PythonIdioms.py", "copies": "1", "size": "1396", "license": "cc0-1.0", "hash": 3439500107487517000, "line_mean": 20.8125, "line_max": 74, "alpha_frac": 0.6511461318, "autogenerated": false, "ratio": 3.088495575221239, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9204338586083037, "avg_score": 0.007060624187640317, "num_lines": 64 }
# 1. Read the names of the json files from the directory; # 2. Print out the json file names. # Import packages: import os import glob import magic import json # Set the working directory to the new GrEx. Print the working directory to confirm: path = 'C:\\Users\Stephan\Desktop\GrEx3' os.chdir(path) print(os.getcwd()) # C:\Users\Stephan\Desktop\GrEx3 # Read list of files in the folder using the os package: print(os.listdir()) # Various ways to pull out only the json files. # 1. Use os package and create a dictionary by file type # (this method won't work if any file has a '.' in the file name): files = os.listdir() files_dict = dict(file.split('.') for file in files) json_dict = {k:v for (k,v) in files_dict.items() if v == 'json'} print(json_dict) # 2. Use glob to get a list: print(glob.glob('*.json')) # 3. If the folder is huge and memory usage or speed is a concern, you can iterate over the files # in the folder without storing them to memory using iglob: for json_file in glob.iglob('*.json'): print (json_file) # Validate they are .json # 1. Use mime / magic mime = magic.Magic(mime=True) print(mime.from_file('100506.json')) # 2. Create a function to find the fake json: def check_json(file): try: json.load(file) except ValueError: return False return True for json_file in json_list: with open(json_file) as json_data: if check_json(json_data) == False: print('File named ' + json_file + ' is not really a json file.') # File named fakeJSON.json is not really a json file.
{ "repo_name": "sgranitz/nw", "path": "predict420/dne5.py", "copies": "2", "size": "1576", "license": "mit", "hash": -7167821400173000000, "line_mean": 27.6545454545, "line_max": 98, "alpha_frac": 0.6840101523, "autogenerated": false, "ratio": 3.283333333333333, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4967343485633333, "avg_score": null, "num_lines": null }
## 1. Recap ## import pandas as pd import matplotlib.pyplot as plt unrate = pd.read_csv('unrate.csv') unrate['DATE'] = pd.to_datetime(unrate['DATE']) plt.plot(unrate['DATE'].head(12),unrate['VALUE'].head(12)) plt.xticks(rotation=90) plt.xlabel('Month') plt.ylabel('Unemployment Rate') plt.title('Monthly Unemployment Trends, 1948') ## 2. Matplotlib Classes ## import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(2,1,1) ax2 = fig.add_subplot(2,1,2) plt.show() ## 4. Adding Data ## fig = plt.figure() ax1 = fig.add_subplot(2,1,1) ax2 = fig.add_subplot(2,1,2) ax1.plot(unrate['DATE'].head(12),unrate['VALUE'].head(12)) ax2.plot(unrate['DATE'].iloc[12:24],unrate['VALUE'].iloc[12:24]) plt.show() ## 5. Formatting And Spacing ## fig = plt.figure(figsize=(12,6)) ax1 = fig.add_subplot(2,1,1) ax2 = fig.add_subplot(2,1,2) ax1.plot(unrate[0:12]['DATE'], unrate[0:12]['VALUE']) ax1.set_title('Monthly Unemployment Rate, 1948') ax2.plot(unrate[12:24]['DATE'], unrate[12:24]['VALUE']) ax2.set_title('Monthly Unemployment Rate, 1949') plt.show() ## 6. Comparing Across More Years ## fig = plt.figure(figsize=(12,12)) x = [0,12,24,36,48] y = [12,24,36,48,60] for i in range(5): ax = fig.add_subplot(5,1,(i+1)) ax.plot(unrate[x[i]:y[i]]['DATE'],unrate[x[i]:y[i]]['VALUE']) plt.show() ## 7. Overlaying Line Charts ## unrate['MONTH'] = unrate['DATE'].dt.month fig = plt.figure(figsize=(6,3)) plt.plot(unrate[0:12]['MONTH'], unrate[0:12]['VALUE'],c='red') plt.plot(unrate[12:24]['MONTH'], unrate[12:24]['VALUE'],c='blue') plt.show() ## 8. Adding More Lines ## fig = plt.figure(figsize=(10,6)) x = [0,12,24,36,48] y = [12,24,36,48,60] color = ['red','blue','green','orange','black'] for i in range(5): plt.plot(unrate[x[i]:y[i]]['MONTH'],unrate[x[i]:y[i]]['VALUE'],c = color[i]) plt.show() ## 9. Adding A Legend ## fig = plt.figure(figsize=(10,6)) colors = ['red', 'blue', 'green', 'orange', 'black'] for i in range(5): start_index = i*12 end_index = (i+1)*12 label = str(1948 + i) subset = unrate[start_index:end_index] plt.plot(subset['MONTH'], subset['VALUE'], c=colors[i],label=label) plt.legend(loc='upper left') plt.show() ## 10. Final Tweaks ## fig = plt.figure(figsize=(10,6)) colors = ['red', 'blue', 'green', 'orange', 'black'] for i in range(5): start_index = i*12 end_index = (i+1)*12 subset = unrate[start_index:end_index] label = str(1948 + i) plt.plot(subset['MONTH'], subset['VALUE'], c=colors[i], label=label) plt.legend(loc='upper left') plt.title("Monthly Unemployment Trends, 1948-1952") plt.xlabel('Month, Integer') plt.ylabel('Unemployment Rate, Percent') plt.show()
{ "repo_name": "vipmunot/Data-Analysis-using-Python", "path": "Exploratory Data Visualization/Multiple plots-216.py", "copies": "1", "size": "2691", "license": "mit", "hash": -3005192965135424000, "line_mean": 26.1919191919, "line_max": 80, "alpha_frac": 0.6358231141, "autogenerated": false, "ratio": 2.4916666666666667, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.36274897807666673, "avg_score": null, "num_lines": null }
# 1. Reebok is designing a new type of Crossfit shoe, the Nano X. The fixed cost for the # production will be $24,000. The variable cost will be $36 per pair of shoes. The shoes will # sell for $107 for each pair. Using Python, graph the cost and revenue functions and # determine how many pairs of sneakers will have to be sold for the company to break even on # this new line of shoes. import matplotlib.pyplot as plt import math # Expenses # y = 36x + 24000 exp_slope = 36 exp_int = 24000 exp_x0 = 0 exp_y0 = exp_slope * exp_x0 + exp_int exp_x1 = 1000 exp_y1 = exp_slope * exp_x1 + exp_int # Revenue # y = 107x rev_slope = 107 rev_int = 0 rev_x0 = 0 rev_y0 = rev_slope * rev_x0 + rev_int rev_x1 = 1000 rev_y1 = rev_slope * rev_x1 + rev_int # Breakeven # 107x = 36x + 24000 # 71x = 24000 # x = 338.028 # y = 107(338.028) = 36169.014 be_x = 24000 / 71 be_y = 107 * be_x # Plot the lines fig, shoe = plt.subplots() shoe.scatter([exp_x0, exp_x1], [exp_y0, exp_y1], c = 'r') shoe.plot([exp_x0, exp_x1], [exp_y0, exp_y1], c = 'r', alpha = 0.3) shoe.scatter([rev_x0, rev_x1], [rev_y0, rev_y1], c = 'g') shoe.plot([rev_x0, rev_x1], [rev_y0, rev_y1], c = 'g', alpha = 0.3) shoe.scatter([be_x], [be_y], c = 'b', s = 100) plt.xlim(0, 750) plt.ylim(0, 75000) plt.show() print("To break even, Reebok must sell", math.ceil(be_x), "shoes.") # 2. Nicole invests a total of $17,500 in three products. She invests one part in a mutual fund # which has an annual return of 11%. She invests the second part in government bonds at 7% # per year. The third part she puts in CDs at 5% per year. She invests twice as much in the # mutual fund as in the CDs. In the first year Nicole's investments bring a total return of $1495. # How much did she invest in each product? import numpy as np from numpy.linalg import inv import matplotlib.pyplot as plt # x + y + z = 17500 # 0.11x + 0.07y + 0.05z = 1495 # x - 2z = 0 a = inv(np.matrix('1 1 1; 11 7 5; 1 0 -2')) b = np.array([17500, 149500, 0]) res = a.dot(b) print("mutual funds=", res[0, 0], "gov't bonds =", res[0, 1], "CDs =", res[0, 2]) labels = 'Mut Funds', "Gov't Bonds", 'CDs' sizes = [res[0, 0], res[0, 1], res[0, 2]] colors = ['lightskyblue', 'pink', 'yellowgreen'] plt.pie(sizes, labels = labels, colors = colors, autopct = '%1.1f%%', startangle = 140) plt.axis('equal') plt.show() # 3. A company has 252 sales reps, each to be assigned to one of four marketing teams. If the first # team is to have three times as many members as the second team and the third team is to # have twice as many members as the fourth team, how can the members be distributed among # the teams? import pandas as pd # w + x + y + z = 252 # w = 3x # y = 2z # 3x + x + 2z + z = 252 # 4x + 3z = 252 # 4x = 252 - 3z # x = 63 - 3/4z # w = 3 * (63 - 3/4z) # w = 189 - 9/4z res = [] for z in range(253): z = float(z) x = float(63 - 3 * z / 4) y = float(2 * z) w = float(189 - 9 * z / 4) a,b = False,False if (w > 0) & (x > 0) & (y > 0) & (z > 0): a = True if (w.is_integer()) & (x.is_integer()) & (y.is_integer()) & (z.is_integer()): b = True if a & b: res.append([w, x, y, z]) teams = ['team1', 'team2', 'team3', 'team4'] print(pd.DataFrame(res, columns = teams)) pd.DataFrame(res, columns = teams).plot(kind = 'bar', stacked = True) # 4. A company makes three types of artisanal chocolate bars: cherry, almond, and raisin. Matrix # A gives the amount of ingredients in one batch. Matrix B gives the costs of ingredients from # suppliers J and K. Using Python, calculate the cost of 100 batches of each candy using # ingredients from supplier K. import numpy as np a = np.matrix('6 8 1; 6 4 1; 5 7 1') b = np.matrix('4 3; 4 5; 2 2') batch = a.dot(b) print("100 cherry =", batch[0, 1] * 100, "100 almond =", batch[1, 1] * 100, "100 raisin =", batch[2, 1] * 100) # 5. Welsh-Ryan Arena seats 15,000 people. Courtside seats cost $8, first level seats cost $6, and # upper deck seats cost $4. The total revenue for a sellout is $76,000. If half the courtside seats, # half the upper deck seats, and all the first level seats are sold, then the total revenue is # $44,000. How many of each type of seat are there? import numpy as np from numpy.linalg import inv # x + y + z = 15000 # 8x + 6y + 4z = 76000 # 0.5(8x + 4z) + 6y = 44000 # 4x + 6y + 2z = 44000 a = inv(np.matrix('1 1 1; 8 6 4; 4 6 2')) b = np.array([15000, 76000, 44000]) res = a.dot(b) print("courtside =", res[0, 0], "first level=", res[0, 1], "upper deck =", res[0, 2]) # 6. Due to new environmental restrictions, a chemical company must use a new process to # reduce pollution. The old process emits 6 g of Sulphur and 3 g of lead per liter of chemical # made. The new process emits 2 g of Sulphur and 4 g of lead per liter of chemical made. The # company makes a profit of 25¢ per liter under the old process and 16¢ per liter under the new # process. No more than 18,000 g of Sulphur and no more than 12,000 g of lead can be emitted # daily. How many liters of chemicals should be made daily under each process to maximize # profits? What is the maximum profit? from scipy.optimize import linprog as lp import numpy as np # maximize: 0.25x + 0.16y # subject to: # 6x + 2y <= 18000 # 3x + 4y <= 12000 # x, y >= 0 A = np.array([[6, 2], [3, 4]]) b = np.array([18000, 12000]) liters = lp(np.array([-0.25, -0.16]), A, b) print("old method=", round(liters.x[0], 2), "liters.", "new method=", round(liters.x[1], 2), "liters.") print("Max daily profit=", round(0.25 * liters.x[0] + 0.16 * liters.x[1], 2)) # 7. Northwestern is looking to hire teachers and TA’s to fill its staffing needs for its summer # program at minimum cost. The average monthly salary of a teacher is $2400 and the average # monthly salary of a TA is $1100. The program can accommodate up to 45 staff members and # needs at least 30 to run properly. They must have at least 10 TA’s and may have up to 3 TA’s # for every 2 teachers. Using Python, find how many teachers and TA’s the program should # hire to minimize costs. What is the minimum cost? from scipy.optimize import linprog as lp import numpy as np # minimize: 2400x + 1100y # subject to: # x + y <= 45 # x + y >= 30 # y >= 10 # 2y <= 3x # x, y >= 0 A = np.array([[-1, -1], [-3, 2]]) b = np.array([-30, 0]) x_bounds = (0, 45) y_bounds = (10, 45) hire = lp(np.array([2400, 1100]), A, b, bounds = (x_bounds, y_bounds)) print("Hire", hire.x[0], "teachers.", "Hire", hire.x[1], "TAs.") print("Minimum cost=", 2400 * hire.x[0] + 1100 * hire.x[1]) # 8. To be at his best as a teacher, Roger needs at least 10 units of vitamin A, 12 units of vitamin # B, and 20 units of vitamin C per day. Pill #1 contains 4 units of A and 3 of B. Pill #2 contains # 1 unit of A, 2 of B, and 4 of C. Pill #3 contains 10 units of A, 1 of B, and 5 of C. Pill #1 costs # 6 cents, pill #2 costs 8 cents, and pill #3 costs 1 cent. How many of each pill must Roger take # to minimize his cost, and what is that cost? from scipy.optimize import linprog as lp import numpy as np # minimize: 0.06x + 0.08y + 0.01z # subject to: # 4x + y + 10z >= 10 # 3x + 2y + z >= 12 # 4y + 5z >= 20 # x, y, z >= 0 A = np.array([[-4, -1, -10], [-3, -2, -1], [0, -4, -5]]) b = np.array([-10, -12, -20]) pills = lp(np.array([0.06, 0.08, 0.01]), A, b) print("Pill #1=", pills.x[0], "Pill #2=", pills.x[1], "Pill #3=", pills.x[2],) print("Minimum cost=", 0.06 * pills.x[0] + 0.08 * pills.x[1] + 0.01 * pills.x[2]) # 9. An electronics store stocks high-end DVD players, surround sound systems, and televisions. # They have limited storage space and can stock a maximum of 210 of these three machines. # They know from past experience that they should stock twice as many DVD players as stereo # systems and at least 30 television sets. If each DVD player sells for $450, each surround # sound system sells for $2000, and each television sells for $750, how many of each should be # stocked and sold for maximum revenues? What is the maximum revenue? from scipy.optimize import linprog as lp import numpy as np # maximize: 450x + 2000y + 750z # subject to: # x + y + z <= 210 # x >= 2y # z >= 30 # x, y, z >= 0 A = np.array([[1, 1, 1], [-1, 2, 0], [0, 0, -1]]) b = np.array([210, 0, -30]) units = lp(np.array([-450, -2000, -750]), A, b) print("DVDs =", units.x[0], "SS Systems=", units.x[1], "TVs =", units.x[2],) print("Maximum revenue=", 450 * units.x[0] + 2000 * units.x[1] + 750 * units.x[2]) # 10. A fast-food company is conducting a sweepstakes, and ships two boxes of game pieces to a # particular franchise. Box A has 4% of its contents being winners, while 5% of the contents of # box B are winners. Box A contains 27% of the total tickets. The contents of both boxes are # mixed in a drawer and a ticket is chosen at random. Using Python, find the probability it # came from box A if it is a winner. is_box_a = 0.27 box_a_win = 0.04 box_b_win = 0.05 a = is_box_a * box_a_win b = (1 - is_box_a) * box_b_win prob = a / (a + b) print("Probability that winner came from Box A is", round(prob * 100, 3), "%.") # Heatmap of probabilities for drawing random card import pandas as pd import seaborn as sns a2 = is_box_a * (1 - box_a_win) b2 = (1 - is_box_a) * (1 - box_b_win) prob2 = a / (a + b + a2 + b2) prob3 = b / (a + b + a2 + b2) prob4 = a2 / (a + b + a2 + b2) prob5 = b2 / (a + b + a2 + b2) df = pd.DataFrame([[prob2, prob4], [prob3, prob5]], index = ['Box A', 'Box B'], columns = ['Winner', 'Loser']) sns.heatmap(df)
{ "repo_name": "sgranitz/northwestern", "path": "predict400/ex1.py", "copies": "2", "size": "9866", "license": "mit", "hash": 4316507420852708000, "line_mean": 32.1851851852, "line_max": 100, "alpha_frac": 0.6206371753, "autogenerated": false, "ratio": 2.6601889338731444, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9220313665970495, "avg_score": 0.012102488640529768, "num_lines": 297 }
#1. class LR_LinearDecay(): ''' Function : -Learning rate decay linearly(a constant factor) after each epoch -Eg. LR= 5, 5.8, 5.6, 5.4, ........ ''' def __init__(self, min_lr=1e-5, max_lr=1e-2, epochs=None): super().__init__() self.min_lr = min_lr self.max_lr = max_lr self.total_iterations = epochs def get_lr(self, epoch_i): '''Return the updated learning rate.''' self.iteration = epoch_i x = self.iteration / self.total_iterations return self.max_lr - (self.max_lr-self.min_lr) * x #2. class LR_StepDecay(): ''' Function : -Learning rate decay stepwise(a varing factor) after every few epochs - Eg. LR= 5, 5, 5, 2.5, 2.5, 2.5, 1.25, 1.25, 1.25, ...... ''' def __init__(self, max_lr=1e-2, step_size=3, decay_factor=2): super().__init__() self.max_lr = max_lr self.step_size = step_size # meaning: update happens after every `step_size` iterations self.decay_factor = decay_factor def get_lr(self, epoch_i): '''Return the updated learning rate.''' self.iteration = epoch_i x = self.iteration / self.step_size return self.max_lr / (self.decay_factor ** int(x) ) #3. class LR_ExponentialDecay(): ''' Function : Learning rate decay exponentially( exp(k*t) ) after each epoch ''' def __init__(self, max_lr=1e-2, decay_factor=0.1): super().__init__() self.max_lr = max_lr self.decay_factor = decay_factor def get_lr(self, epoch_i): '''Return the updated learning rate.''' return self.max_lr / math.exp(self.decay_factor*epoch_i ) #4. class LR_Cyclical(): ''' Function - This implements 2 techniques: 1.Linear annealing(to better converge at minima) 2.Learning rate linear restart(to escape local minima) ''' def __init__(self, min_lr=1e-5, max_lr=1e-2, step_size=10, mode='triangular', gamma=1., scale_fn=None, scale_mode='cycle'): super(CyclicLR, self).__init__() import math self.min_lr = min_lr self.max_lr = max_lr self.step_size = step_size self.mode = mode if scale_fn == None: if(self.mode == 'triangular'): self.scale_fn = lambda x: 1. elif(self.mode == 'triangular2'): self.scale_fn = lambda x: 1/(2.**(x-1)) elif(self.mode == 'exp_range'): self.scale_fn = lambda x: gamma**(x) else: self.scale_fn = scale_fn def get_lr(self, epoch_i): cycle = math.floor(1 + epoch_i/(2*self.step_size)) x = math.abs (epoch_i/self.step_size - 2*cycle + 1) return self.base_lr + (self.max_lr-self.min_lr) * (1-x) * self.scale_fn(cycle) #5. class LR_StochasticGradientDescentWithWarmRestarts(): ''' Function - This implements 2 techniques: 1.Cosine annealing(to better converge at minima) 2.Learning rate sharp restart(to escape local minima) ''' def __init__(self, min_lr, max_lr, epoch_steps=10): self.min_lr = min_lr self.max_lr = max_lr self.epoch_steps = epoch_steps # restarts after every `epoch_steps` no. of epochs self.batch_since_restart = 0 def get_lr(self, epoch_i): '''Calculate the learning rate.''' self.batch_since_restart = epoch_i % epoch_steps fraction_to_restart = self.batch_since_restart / (epoch_steps) return self.min_lr + 0.5 * (self.max_lr - self.min_lr) * (1 + np.cos(fraction_to_restart * np.pi)) ''' Example. >> epoch_n = 50 >> lr = LR_LinearDecay(epochs = epoch_n) >> for epoch_i in range(1,epoch_n+1): learning_rate = lr.get_lr(epoch_i = epoch_i ) '''
{ "repo_name": "iamharshit/ML_works", "path": "ALGOs/LearningRate_Decay.py", "copies": "1", "size": "4209", "license": "mit", "hash": -2420692056237894700, "line_mean": 28.5, "line_max": 127, "alpha_frac": 0.5141363744, "autogenerated": false, "ratio": 3.402586903799515, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9182491942924181, "avg_score": 0.04684626705506664, "num_lines": 138 }
#1. def print_n(string, num): count = 0 while count < num: print string count += 1 #2. def bottles(num): while num >= 1: print '{} bottles of soda on the wall'.format(num) print '{} bottles of soda'.format(num) print 'Take one down, pass it around' num -= 1 print '{} bottles of soda on the wall'.format(num) print '' return #3. def factorial(num): current = 1 total = 1 while current <= num: total *= current current += 1 return total #4a. def password(): answer = raw_input('Enter password: ') while answer != 'please': print 'Invalid password' answer = raw_input('Enter password: ') print 'Access granted.' return #4b. def password2(): attempts = 5 while attempts > 0: answer = raw_input('Enter password: ') if answer.lower() == 'please': break else: attempts -= 1 print 'Invalid password. {} attempts remaining'.format(attempts) if attempts == 0: print 'Access Denied' else: print 'Access Granted' return #5. def sum_of_odd(n): current = 1 total = 0 while current <= n: total += current current += 2 return total #6. def biggest(): biggest = -10000000000000000000000000000000000000 while True: answer = raw_input('Enter a number: ') if answer == '': break elif int(answer) > biggest: biggest = int(answer) elif int(answer) < biggest: pass return biggest #Fibonacci challenge def fib(n): count = 1 num1 = 1 temp_num1 = 1 num2 = 1 temp_num2 = 1 while count <= n: print num1 temp_num2 = num1 + num2 temp_num1 = num2 num1 = temp_num1 num2 = temp_num2 count += 1 return #Prime number challenge def is_prime(number): count = 2 while count < number: if number % count > 0: count +=1 elif number % count == 0: return False return True
{ "repo_name": "Nethermaker/school-projects", "path": "intro/while_practice.py", "copies": "1", "size": "2322", "license": "mit", "hash": -3711466855598380000, "line_mean": 16, "line_max": 76, "alpha_frac": 0.4900947459, "autogenerated": false, "ratio": 3.935593220338983, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9807391102140312, "avg_score": 0.023659372819734317, "num_lines": 129 }
#1 import pygame from pygame.locals import* import math import random import time #2 shootInterval=15 shootTimer=0 badtimer=100 badtimer1=0 badguys=[] healthvalue=194 acc=[0,0] arrows=[] keys=[False,False,False,False] autoshoot=False playerpos=[100,100] pygame.init() width,height=1000,750 screen=pygame.display.set_mode((width,height)) pygame.mixer.init() #3 player=pygame.image.load("resources/images/dude.png") grass=pygame.image.load("resources/images/grass.png") castle=pygame.image.load("resources/images/castle.png") arrow=pygame.image.load('resources/images/bullet.png') badguyimg1 = pygame.image.load("resources/images/badguy.png") healthbar = pygame.image.load("resources/images/healthbar.png") health=pygame.image.load("resources/images/health.png") badguyimg=badguyimg1 gameover = pygame.image.load("resources/images/gameover.png") gameoverFull=pygame.transform.scale(gameover,(width,height)) youwin = pygame.image.load("resources/images/youwin.png") youwinFull=pygame.transform.scale(youwin,(width,height)) #3.1 hit = pygame.mixer.Sound("resources/audio/explode.wav") enemy = pygame.mixer.Sound("resources/audio/enemy.wav") shoot = pygame.mixer.Sound("resources/audio/shoot.wav") hit.set_volume(0.05) enemy.set_volume(0.05) shoot.set_volume(0.05) pygame.mixer.music.load('resources/audio/moonlight.wav') pygame.mixer.music.play(-1, 0.0) pygame.mixer.music.set_volume(0.25) #4 running = 1 exitcode = 0 while running: time.sleep(0.01) badtimer-=1 #5 screen.fill([0,255,0]) #6 ''' for x in range(width/grass.get_width()+1): for y in range (height/grass.get_height()+1): screen.blit(grass,(x*100,y*100)) ''' for x in range (1,5): screen.blit(castle,(0,height/5*x-50)) #6.1 position=pygame.mouse.get_pos() angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26)) playerrot = pygame.transform.rotate(player, 360-angle*57.29) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) #6.2 for bullet in arrows: velx=math.cos(bullet[0])*5 vely=math.sin(bullet[0])*5 bullet[1]+=velx bullet[2]+=vely if bullet[1]<-64 or bullet[1]>640 or bullet[2]<-64 or bullet[2]>480: del bullet for projectile in arrows: arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29) screen.blit(arrow1, (projectile[1], projectile[2])) #6.3 if badtimer==0: badguys.append([width, random.randint(50,height-50)]) badtimer=100-(badtimer1*2) if badtimer1>=35: badtimer1=35 else: badtimer1+=5 index=0 for badguy in badguys: if badguy[0]<-64: badguys.pop(index) badguy[0]-=10 badrect=pygame.Rect(badguyimg.get_rect()) badrect.top=badguy[1] badrect.left=badguy[0] if badrect.left<64: healthvalue -= random.randint(5,20) badguys.pop(index) hit.play() #6.3.2 index1=0 for bullet in arrows: bullrect=pygame.Rect(arrow.get_rect()) bullrect.left=bullet[1] bullrect.top=bullet[2] if badrect.colliderect(bullrect): acc[0]+=1 badguys.pop(index) arrows.pop(index1) enemy.play() index1+=1 index+=1 for badguy in badguys: screen.blit(badguyimg, badguy) #6.4 font=pygame.font.Font(None,24) survivedtext = font.render(str((90000-pygame.time.get_ticks())/60000)+":"+str((90000-pygame.time.get_ticks())/1000%60).zfill(2), True, (0,0,0)) textRect = survivedtext.get_rect() textRect.topright=[635,5] screen.blit(survivedtext, textRect) #6.5 screen.blit(healthbar, (5,5)) for health1 in xrange(healthvalue): screen.blit(health,(health1+8,8)) #7 pygame.display.flip() #8 for event in pygame.event.get(): if event.type==pygame.MOUSEBUTTONDOWN: autoshoot=True if event.type==pygame.MOUSEBUTTONUP: autoshoot=False if event.type==pygame.QUIT: pygame.quit() exit(0) if event.type == pygame.KEYDOWN: if event.key==K_w: keys[0]=True elif event.key==K_a: keys[1]=True elif event.key==K_s: keys[2]=True elif event.key==K_d: keys[3]=True if event.type == pygame.KEYUP: if event.key==pygame.K_w: keys[0]=False elif event.key==pygame.K_a: keys[1]=False elif event.key==pygame.K_s: keys[2]=False elif event.key==pygame.K_d: keys[3]=False if autoshoot and shootTimer<=0: position=pygame.mouse.get_pos() acc[1]+=1 arrows.append([math.atan2(position[1]-(playerpos1[1]+32),position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos1[1]+32]) shoot.play() shootTimer=shootInterval shootTimer-=1 #9 if keys[0]: playerpos[1]-=5 elif keys[2]: playerpos[1]+=5 if keys[1]: playerpos[0]-=5 elif keys[3]: playerpos[0]+=5 #10 if pygame.time.get_ticks()>=90000: running=0 exitcode=1 if healthvalue<=0: running=0 exitcode=0 if acc[1]!=0: accuracy=acc[0]*1.0/acc[1]*100 else: accuracy=0 #11 if exitcode==0: pygame.font.init() font = pygame.font.Font(None, 24) text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0)) textRect = text.get_rect() textRect.centerx = screen.get_rect().centerx textRect.centery = screen.get_rect().centery+24 screen.blit(gameoverFull, (0,0)) screen.blit(text, textRect) else: pygame.font.init() font = pygame.font.Font(None, 24) text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0)) textRect = text.get_rect() textRect.centerx = screen.get_rect().centerx textRect.centery = screen.get_rect().centery+24 screen.blit(youwinFull, (0,0)) screen.blit(text, textRect) while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit(0) pygame.display.flip()
{ "repo_name": "milkmeat/thomas", "path": "rabbit game/game.py", "copies": "1", "size": "6710", "license": "mit", "hash": -2836063987357558000, "line_mean": 29.6509433962, "line_max": 147, "alpha_frac": 0.5812220566, "autogenerated": false, "ratio": 3.068129858253315, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.41493519148533153, "avg_score": null, "num_lines": null }
# 1. Select 4 bounding boxes around each dot # 2. For each frame: # a. search some radius around the bounding box # b. select a new bounding box from your search such that the SDD is minimized # c. compute projective transformation based on the centers of each bounding box # d. warp an image using that projection transformation # e. output to png file import cv2 import numpy as np import sys import os import math WHITE = [255,255,255] def GetPointsFromBoxes(boxes): p = np.zeros((4,2), dtype = "float32") for i in range(len(boxes)): p[i] = [boxes[i][0] + boxes[i][2]/2.0, boxes[i][1] + boxes[i][3]/2.0] return p # find the sum of squares difference between two images def SumOfSquaresDifference(im1, im2): diffIm = (im2 - im1)**2 return np.sum(diffIm) # find the best bounding box in the next frame within a given radius # that most closely matches the current bounding box def BestBoundingBoxInRegion(prevFrame, curFrame, box, radius): oldRegion = prevFrame[int(box[1]):int(box[1]+box[3]), int(box[0]):int(box[0]+box[2])] testRegion = curFrame[(int(box[1]) - radius):(int(box[1]+box[3]) - radius), (int(box[0]) - radius):(int(box[0]+box[2]) - radius)] bestSSD = math.inf newBox = ((int(box[0]) - radius), (int(box[1]) - radius), box[2], box[3]) h,w = curFrame.shape for i in range(-radius,radius): for j in range(-radius,radius): if ((int(box[1]) - i) < 0 or (int(box[0]) - j) < 0 or (int(box[1]+box[3]) - i) >= h or (int(box[0]+box[2]) - j) >= w): continue testRegion = curFrame[(int(box[1]) - i):(int(box[1]+box[3]) - i), (int(box[0]) - j):(int(box[0]+box[2]) - j)] #the harris corners for both regions oldCorners = cv2.cornerHarris(oldRegion,4,1,0.04) testCorners = cv2.cornerHarris(testRegion,4,1,0.04) testSSD = SumOfSquaresDifference(oldCorners, testCorners) if (testSSD < bestSSD): bestSSD = testSSD newBox = ((int(box[0]) - j), (int(box[1]) - i), box[2], box[3]) return newBox # selects 4 bounding boxes around each dot # NOTE: when selecting bounding box, select from the center of the dot! def SelectBoundingBoxes(stillFrame): cv2.namedWindow('ROIs') r1 = cv2.selectROI('ROIs', stillFrame) r2 = cv2.selectROI('ROIs', stillFrame) r3 = cv2.selectROI('ROIs', stillFrame) r4 = cv2.selectROI('ROIs', stillFrame) return [r1, r2, r3, r4] def CreateComposite(source, inputImage, outputName, startFrame, numFrames, radius): filename, fileExtension = os.path.splitext(outputName) #spin to the start frame, no checks here for sp in range(startFrame): retSource, frameSource = source.read() frameSource = cv2.resize(frameSource, (1280, 720)) # frameSource = cv2.copyMakeBorder(frameSource, radius+1, radius+1, radius+1, radius+1, cv2.BORDER_CONSTANT, value = WHITE) #image dimensions h,w,d = inputImage.shape #the image coordinates that will be transformed imagePoints = [ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ] #the point information for this frame and last frame framePoints = [] framePointsPrev = [] #storage for the boxes boxes = SelectBoundingBoxes(frameSource) #signifies the first frame firstFrame = True for frameIndex in range(numFrames): oldSource = frameSource #Read the source video by a frame retSource, frameSource = source.read() if (not retSource): break frameSource = cv2.resize(frameSource, (1280, 720)) # frameSource = cv2.copyMakeBorder(frameSource, radius+1, radius+1, radius+1, radius+1, cv2.BORDER_CONSTANT, value = WHITE) oldGray = cv2.cvtColor(oldSource, cv2.COLOR_BGR2GRAY) newGray = cv2.cvtColor(frameSource, cv2.COLOR_BGR2GRAY) outIm = frameSource for bindex in range(len(boxes)): print('hello ' + str(frameIndex) + ' ' + str(bindex) + '\n') boxes[bindex] = BestBoundingBoxInRegion(oldGray, newGray, boxes[bindex], radius) cv2.rectangle(outIm, (boxes[bindex][0], boxes[bindex][1]), (boxes[bindex][2] + boxes[bindex][0], boxes[bindex][3] + boxes[bindex][1]), (255,0,255)) pTarget = GetPointsFromBoxes(boxes) pInput = np.array([[0.0, 0.0], [w, 0.0], [w, h], [0.0, h]], dtype = "float32") M = cv2.getPerspectiveTransform(pInput, pTarget) warped = cv2.warpPerspective(inputImage, M, (1280, 720)) warpmatte = warped == 0 outIm = warped + outIm * warpmatte cv2.imwrite(filename + '_' + str(frameIndex) + fileExtension, outIm) if __name__ == "__main__": vidFile = sys.argv[1] startFrame = int(sys.argv[2]) numFrames = int(sys.argv[3]) searchRadius = int(sys.argv[4]) outFileName = sys.argv[5] inputImageName = sys.argv[6] source = cv2.VideoCapture(vidFile) inputImage = cv2.imread(inputImageName) CreateComposite(source,inputImage, outFileName, startFrame, numFrames, searchRadius)
{ "repo_name": "JasonKraft/CVFall2017", "path": "hw3/problem2.py", "copies": "1", "size": "4907", "license": "mit", "hash": -5599516873562585000, "line_mean": 35.0882352941, "line_max": 153, "alpha_frac": 0.6574281638, "autogenerated": false, "ratio": 3.0048989589712187, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4162327122771219, "avg_score": null, "num_lines": null }
### (-1). Setup import json from rhine.instances import * from rhine.datatypes import * from rhine.functions import * client = instantiate('CEFPUFKMUVJBNZMFUOPOLZEOM') # This API key will be disabled shortly after the demo - register your own for free at www.rhine.io. ### (0). Datasets articles = json.loads(open('articles.json').read()) images = json.loads(open('images.json').read()) profiles = json.loads(open('profiles.json').read()) ### (1). Search # Search for news articles relating to a given topic. def search(query): # Iterate through each article, assigning a distance score. for a in articles: # Compute the distance from the user's query to the article text. a['distance'] = client.run(distance(entity(query), text(a['text']))) # If no relation is found, assign a distance of 100 (the maximum) if a['distance'] is None: a['distance'] = 100 # Return the article with the lowest distance. return min(articles, key = lambda a: a['distance']) # (examples: 'politics', 'celebrity') ### (2). Filtration # Find users interested in something. def interested_in(query): # Iterate through the user profiles, checking if any of their interests are related to what we want to know about. for p in profiles: # Compute the distance from the user's query to the profile's interests. p['distance'] = min(client.pipeline([distance(entity(i), entity(query)) for i in p['interests']])) # If no relation is found, assign a distance of 100 (the maximum) if p['distance'] is None: p['distance'] = 100 # Return all users with distance lower than certain threshold return [p for p in profiles if p['distance'] < 10] # (examples: 'religion', 'food') ### (3). Sorting # Automatic clustering! def cluster(): return client.run(clustering([entity(i) for p in profiles for i in p['interests']])) ### (4). Knowledge # Filter images by type. def animals(): return [i for i in images if client.run(subclass(image.fromurl(i), entity('animal')))] ### (5). Inference / Prediction # Match articles to users, just with distance. def recommend(user): profile = [p for p in profiles if p['name'] == user][0] return min(articles, key = lambda a: client.run(distance(text(a['text']), \ grouped(entity(profile['interests'][0]), \ entity(profile['interests'][1]), \ entity(profile['interests'][2]))))) # (examples: 'Alex', 'Mary' ~~)
{ "repo_name": "Speare/rhine-python", "path": "examples/demo.py", "copies": "1", "size": "2418", "license": "bsd-3-clause", "hash": 5204005192527133000, "line_mean": 30.4025974026, "line_max": 150, "alpha_frac": 0.6807278743, "autogenerated": false, "ratio": 3.5043478260869567, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46850757003869564, "avg_score": null, "num_lines": null }
## 1. Shared Indexes ## import pandas as pd fandango = pd.read_csv('fandango_score_comparison.csv') print(fandango.head(2)) print(fandango.index) ## 2. Using Integer Indexes to Select Rows ## fandango = pd.read_csv('fandango_score_comparison.csv') first_last = fandango.iloc[[0,len(fandango)-1]] ## 3. Using Custom Indexes ## fandango = pd.read_csv('fandango_score_comparison.csv') fandango_films = fandango.set_index(keys = 'FILM',inplace = False,drop = False) print(fandango_films.index) ## 4. Using a Custom Index for Selection ## best_movies_ever = fandango_films.loc[['The Lazarus Effect (2015)','Gett: The Trial of Viviane Amsalem (2015)','Mr. Holmes (2015)']] ## 5. Apply() Logic Over the Columns in a Dataframe ## import numpy as np # returns the data types as a Series types = fandango_films.dtypes # filter data types to just floats, index attributes returns just column names float_columns = types[types.values == 'float64'].index # use bracket notation to filter columns to just float columns float_df = fandango_films[float_columns] # `x` is a Series object representing a column deviations = float_df.apply(lambda x: np.std(x)) print(deviations) ## 6. Apply() Logic Over Columns: Practice ## double_df = float_df.apply(lambda x: x*2) print(double_df.head(1)) halved_df = float_df.apply(lambda x:x/2) print(halved_df.head(1)) ## 7. Apply() Over Dataframe Rows ## rt_mt_user = float_df[['RT_user_norm', 'Metacritic_user_nom']] rt_mt_deviations = rt_mt_user.apply(lambda x: np.std(x), axis=1) print(rt_mt_deviations[0:5]) rt_mt_means = float_df[['RT_user_norm', 'Metacritic_user_nom']].apply(lambda x:np.mean(x), axis = 1) print(rt_mt_means.head())
{ "repo_name": "vipmunot/Data-Analysis-using-Python", "path": "Data Analysis with Pandas Intermediate/Pandas Internals_ Dataframes-146.py", "copies": "1", "size": "1675", "license": "mit", "hash": 499692301594185900, "line_mean": 31.2307692308, "line_max": 132, "alpha_frac": 0.7170149254, "autogenerated": false, "ratio": 2.7016129032258065, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39186278286258064, "avg_score": null, "num_lines": null }
# 1. Size of vocabulary file # 2. Name of vocabulary file # 3. The input file name # 4. The number of sentences in input file # 5. The window size # 6. The position from which I will start my work. # 7. The name of the file to which I would write. import sys, itertools import struct #import contextlib, mmap vocab_size=int(sys.argv[1]) vocab_dict=dict((v.strip(),i+1) for i,v in enumerate(open(sys.argv[2], "r", 1<<20))) text_filename=sys.argv[3] sentence_count=int(sys.argv[4]) window_size=int(sys.argv[5]) starting_position=int(sys.argv[6]) increment_size=int(sys.argv[7]) outfile=open(sys.argv[8], "wb", 100<<20) min_length_sentence=int(sys.argv[9]) max_pos=min(sentence_count, starting_position+increment_size) bos_idx=vocab_size+1 eos_idx=vocab_size+2 packer=struct.Struct('iii') outfile.write(packer.pack(vocab_size, eos_idx, 0)); keyerr_dict={} with open(text_filename, 'rb', 100<<20) as m: # with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as m: # Skip the lines till we reach starting position for _ in xrange(starting_position): m.readline() for _ in xrange(starting_position, max_pos): row=m.readline().strip().split() if len(row)>min_length_sentence: for i,w in enumerate(row): try: w_idx=vocab_dict[w] except KeyError as k: keyerr_dict[w]=None continue for j in itertools.chain(xrange(-window_size, 0), xrange(1,window_size+1)): e=i+j if e < 0: outfile.write(packer.pack(w_idx, bos_idx, j)) elif e >= len(row): outfile.write(packer.pack(w_idx, eos_idx, j)) else: try: v=vocab_dict[row[e]] except KeyError as k: continue outfile.write(packer.pack(w_idx, v, j)) outfile.close() if len(keyerr_dict): print >> sys.stderr, str(keyerr_dict.keys())
{ "repo_name": "se4u/mvlsa", "path": "src/extract_count/print_cooccurence_rows.py", "copies": "1", "size": "2203", "license": "mit", "hash": -3806868465127870500, "line_mean": 39.7962962963, "line_max": 95, "alpha_frac": 0.5510667272, "autogenerated": false, "ratio": 3.5589660743134086, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4610032801513409, "avg_score": null, "num_lines": null }
# 1. Something that actually "writes" an integer to memory and can "read" an integer from a memory address # 2. Value - something allowing us to get several integers from memory and interpret them as a thing, or # write a thing out as several integers into memory # 3. A specific type of value: "pointer". Interpretation: location in underlying address space of # whatever type this is pointing to. # 2+3. A function to get a pointer value from any value. # 4. "Reference". System for managing "references", which at least must give us a value for a reference # when we ask for it. Name. Scope. # 5. Scope. ?? Functions. Calling things. # Reference: "name" "scope" "value" # asdf = [1, 2, 3] # My memory manager makes some space for a list with 1, 2, 3 in it. Value X # Now create a reference with name "asdf", the current scope, and value X. # qwerty = asdf # Create a reference with name "qwerty", the current scope, and value...? X. # qwerty[1] = 'hi' ====> qwerty is a reference with value X. Change X to have its second element be 'hi'. # asdf[1] = ? it returns [1, 'hi', 3] # asdf = ['nope'] ====> asdf's value is now Y # # def F(r, s): # r = s + 1 # return r + s # # a = [1,1,1,1,,1,1,1,1] # pa = a.value.getPointer() # b = 4 # a = F(a, b) # # create val(addressX, [thousand element list]) # create ref("a", 0, X) # create val(addressY, 4) # create ref("b", 0, Y) # Call F! *enter scope* [optional: make values X' and Y', copies of X and Y] # create ref("r", 1, X) # --- create ref("r", 1, lookup("a",0)) # --- r = 1 # create ref("s", 1, Y) # create val(addressZ, the value in s, which is at Y and is 4, plus 1, or 5) # update ref("r", 1, Z) # create val(addressA, the value in r (5) plus the value in s (4), or 9) # return # *leave scope* # update ref("a", 0, A) class Memory(object): def getAddressOfUnusedMemoryOfSizeN(self, N): pass def write(self, address, listOfIntegers): pass def read(self, address, N): pass def display(self): print(self.mem) class Value(object): """Represents a fixed size structure written somehow to memory A value has a size, which is the size of the list of integers returned by getData. getSize returns that size. getData queries the underlying memory and builds a list of integers to return. getPointer returns a Value of size 1 whose getData returns a list of size 1 whose element is the address of the memory backing the Value that this pointer Value points to. e.g. if we have a Value X storing a list [3,4] at underlying address 22-23, X.getPointer() returns a Value Y storing a list [22] at underlying address ???whoknows it's not up to us. """ def getSize(self): pass def getData(self): pass def createPointerValue(self): pass def free(self): pass def display(self, name): print(name + " has index "+str(self.address)+" size "+ str(self.size) + " in:") self.mem.display() def clone(self): pass class Reference(object): pass #??? class ReferenceManager(object): # enter scope #??? # leave scope # assign value to reference # get value of reference def __init__(self, mem): self.mem = mem # refs is a stack. Each element is a scope which can have several name:value pairs. # the current scope is peek. Leaving scope is pop (plus cleanup). Entering scope is # push (plus initialization) self.refs = [{}] def setReferenceValue(self, name, value): self.refs[-1][name] = value def getReferenceValue(self, name): return self.refs[-1][name] def enterScopeByValue(self, previousScopeNamesOfParameterValues, newScopeParameterNames): newScope = {} for parameterName, previousParameterName in zip(newScopeParameterNames, previousScopeNamesOfParameterValues): referenceValue = self.getReferenceValue(previousParameterName).clone() newScope[parameterName] = referenceValue self.refs.append(newScope) def enterScope(self, previousScopeNamesOfParameterValues, newScopeParameterNames): newScope = {} for parameterName, previousParameterName in zip(newScopeParameterNames, previousScopeNamesOfParameterValues): referenceValue = self.getReferenceValue(previousParameterName) newScope[parameterName] = referenceValue self.refs.append(newScope) def leaveScope(self): cleanup = self.refs.pop() # clean this shit up # a = 1 # aPlus1 = a + 1 # referenceManager.enterScope(["b", "c"], ["a", "aPlus1"]) # class PythonFixedSizeListOfIntegersMemory(Memory): def __init__(self, size): self.mem = [0]*size self.used = [0]*size self.size = size self.EOM = "EOM Addressing past end of memory" self.DEFRAG = "DEFRAG Memory too fragrmented; Not enough executive blocks" def getAddressOfUnusedMemoryOfSizeN(self, N): self.rangeTooLarge(0,N) unusedSize = 0 address = 0 while unusedSize < N: if address == self.size: raise Exception(self.EOM) if self.used[address] == 0: unusedSize += 1 else: unusedSize = 0 address += 1 if unusedSize == N: return address - N else: raise Exception(self.DEFRAG) def rangeTooLarge(self,address,N): exclusiveEndAddress = address + N if exclusiveEndAddress > self.size: raise Exception(self.EOM) def markMemoryUsed(self, address, N): for i in range(address, address + N): self.used[i] = 1 def markMemoryUnused(self, address, N): for i in range(address, address + N): self.used[i] = 0 def write(self, address, listOfIntegers): length = len(listOfIntegers) self.rangeTooLarge(address,length) for i in range(length): self.mem[address + i] = listOfIntegers[i] self.markMemoryUsed(address,len(listOfIntegers)) def read(self, address, N): storedData = [0]*N for i in range(N): storedData[i] = self.mem[address + i] return storedData def free(self, address, N): self.markMemoryUnused(address, N) class ArbitrarySizeValue(Value): def __init__(self,mem,data): self.mem = mem self.size = len(data) self.address = self.mem.getAddressOfUnusedMemoryOfSizeN(self.size) self.mem.write(self.address,data) def getSize(self): return self.size def getData(self): return self.mem.read(self.address,self.size) def createPointerValue(self): pointer = PointerValue(self.mem,[self.address]) return pointer def free(self): self.mem.free(self.address,self.size) def clone(self): newValue = ArbitrarySizeValue(self.mem,self.getData()) return newValue # PointerValue should point to a size 1 mem whose data is the index of the thing it's pointing to class PointerValue(ArbitrarySizeValue): def __init__(self, mem, data): super(PointerValue, self).__init__(mem, data) m = PythonFixedSizeListOfIntegersMemory(10) #m.write(3, [1,2,3,4]) #print(m.mem[4]) #returns 2 #r = m.read(3, 4) #print(r) #returns [1,2,3,4] ##m.write(99,[1,2]) #raises Exception m.getAddressOfUnusedMemoryOfSizeN(1) # somehow we have a Value that's a ListOfSizeTwo called v v = ArbitrarySizeValue(m, [6, 8]) vData = v.getData() #print(v.mem.mem) #print(v.mem.used) vPointer = v.createPointerValue() vPointerData = vPointer.getData() vDataAddress = vPointerData[0] otherVData = m.read(vDataAddress, 2) #print(otherVData) # vData and otherVData are equal #print() m = PythonFixedSizeListOfIntegersMemory(10) d = ArbitrarySizeValue(m, [-1]) v = ArbitrarySizeValue(m, [111, 21, 441]) #v.display("v") vp = v.createPointerValue() #vp.display("&v") vpp = vp.createPointerValue() #vpp.display("&&v") w = ArbitrarySizeValue(m, [999]) #w.display("w") wp = w.createPointerValue() #wp.display("&w") vp2 = v.createPointerValue() #vp2.display("&v (2)") vpp2 = vp2.createPointerValue() #vpp2.display("&&v (2)") w.free() vp.free() #m.display() vppp = vpp.createPointerValue() #vppp.display("&&&v") vppp = vpp.createPointerValue() #print("\r[-1, 111, 21, 441, 5, 4, 5, 6, 1, 8]") #vppp.display("vppp") # asdf = [42, 42] # qwerty = asdf <--- # qwerty[0] = 1 <--- # print(asdf) m = PythonFixedSizeListOfIntegersMemory(30) manager = ReferenceManager(m) # asdf = 42+42 manager.setReferenceValue("asdf", ArbitrarySizeValue(m, [42, 42])) # qwerty = <the same reference as> asdf manager.setReferenceValue("qwerty", manager.getReferenceValue("asdf")) # qwerty highest order byte becomes 1 # 9 = 1001 # 65537 = 00000001 00000001 00000000 00000001 ----- 0x01010001 ... 0-9a-f or 16 possibilities 2^4 # boolean is 1 bit # byte is 8 bits # char 8 bits # short 8 bits # int 16 or 32 v = manager.getReferenceValue("qwerty") m.write(v.createPointerValue().getData()[0], [1]) # print asdf print(manager.getReferenceValue("asdf").getData()) # pAsdf = &asdf manager.setReferenceValue("pAsdf", manager.getReferenceValue("asdf").createPointerValue()) # call F(pAsdf) where F is def F(pB): ... manager.enterScopeByValue(["pAsdf"], ["pB"]) # *pB = 99 m.write(manager.getReferenceValue("pB").getData()[0],[99]) # print *pB print(m.read(manager.getReferenceValue("pB").getData()[0],2)) # return manager.leaveScope() # print qwerty print(manager.getReferenceValue("qwerty").getData()) m.display() # F(a+1,b) # def F(lol, hi) # enter scope needs input values and "output" references
{ "repo_name": "petersrinivasan/neopeng", "path": "memory.py", "copies": "1", "size": "9719", "license": "unlicense", "hash": 2201304572703648500, "line_mean": 31.9491525424, "line_max": 117, "alpha_frac": 0.6505813355, "autogenerated": false, "ratio": 3.323871409028728, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9393160890300503, "avg_score": 0.016258370845644972, "num_lines": 295 }
# 1st Activation Function: sigmoid # 2nd Activation Function: softmax # Loss Function: Cross Entropy Loss # Train Algorithm: Batch Gradient Descent # Bias terms are used. # force the result of divisions to be float numbers from __future__ import division # I/O Libraries from os import listdir from os.path import isfile, join # import local python files from read_mnist_data_from_files import * from Utilities import * import numpy as np __author__ = 'c.kormaris' ############### class NNParams: num_input_nodes = 1000 # D: number of nodes in the input layers (aka: no of features) num_hidden_nodes = 3 # M: number of nodes in the hidden layer num_output_nodes = 2 # K: number of nodes in the output layer (aka: no of categories) # Gradient descent parameters eta = 0.001 # the learning rate of gradient descent reg_lambda = 0.01 # the regularization parameter ############### # FUNCTIONS # # Feed-Forward def forward(X, W1, W2): s1 = X.dot(W1.T) # s1: NxM o1 = sigmoid(s1) # o1: NxM grad = sigmoid_output_to_derivative(o1) # the gradient of sigmoid function, grad: NxM o1 = concat_ones_vector(o1) # o1: NxM+1 s2 = o1.dot(W2.T) # s2: NxK o2 = softmax(s2) # o2: NxK return s1, o1, grad, s2, o2 # Helper function to evaluate the total loss of the dataset def loss_function(X, t, W1, W2): # Feed-Forward to calculate our predictions _, _, _, _, o2 = forward(X, W1, W2) # Calculating the loss logprobs = -np.multiply(t, np.log(o2)) data_loss = np.sum(logprobs) # cross entropy loss data_loss *= 2 # for the gradient check to work # Add regularization term to loss (optional) data_loss += NNParams.reg_lambda / 2 * (np.sum(np.square(W1)) + np.sum(np.square(W2))) return data_loss def test(X, W1, W2): # Feed-Forward _, _, _, _, o2 = forward(X, W1, W2) return np.argmax(o2, axis=1) # This function learns the parameter weights W1, W2 for the neural network and returns them. # - iterations: Number of iterations through the training data for gradient descent. # - print_loss: If True, print the loss every 1000 iterations. def train(X, t, W1, W2, iterations=20000, tol=1e-6, print_loss=False): # Run Batch Gradient Descent loss_old = -np.inf for i in range(iterations): W1, W2, _, _ = gradient_descent(X, t, W1, W2) # Optionally print the loss. # This is expensive because it uses the whole dataset, so we don't_train want to do it too often. if print_loss and i % 1000 == 0: loss = loss_function(X, t, W1, W2) print("Cross entropy loss after iteration %i: %f" % (i, loss)) if np.abs(loss - loss_old) < tol: break loss_old = loss return W1, W2 # Update the Weight matrices using Gradient Descent def gradient_descent(X, t, W1, W2): # W1: MxD+1 = num_hidden_nodes X_train num_of_features # W2: KxM+1 = num_of_categories X_train num_hidden_nodes # Feed-Forward _, o1, grad, _, o2 = forward(X, W1, W2) # Back-Propagation #sum1 = np.matrix(np.sum(t_train, axis=1)).T # sum1: Nx1 #t_train = np.matlib.repmat(sum1, 1, K) # t_train: NxK, each row contains the same sum values in each column #delta1 = np.multiply(o2, t_train) - t_train # delta1: NxK delta1 = o2 - t # delta1: NxK, since t_train is one-hot matrix, then t_train=1, so we can omit it W2_reduce = W2[np.ix_(np.arange(W2.shape[0]), np.arange(1, W2.shape[1]))] # skip the first column of W2: KxM delta2 = np.dot(delta1, W2_reduce) # delta2: NxM delta3 = np.multiply(delta2, grad) # element-wise multiplication, delta3: NxM dW1 = np.dot(delta3.T, X) # MxD+1 dW2 = np.dot(delta1.T, o1) # KxM+1 # Add regularization terms dW1 = dW1 + NNParams.reg_lambda * W1 dW2 = dW2 + NNParams.reg_lambda * W2 # Update gradient descent parameters W1 = W1 - NNParams.eta * dW1 W2 = W2 - NNParams.eta * dW2 return W1, W2, dW1, dW2 def gradient_check(X, t, W1, W2): _, _, gradEw1, gradEw2 = gradient_descent(X, t, W1, W2) epsilon = 1e-6 # gradient_check for parameter W1 numgradEw1 = np.zeros(W1.shape) for i in range(W1.shape[0]): for j in range(W1.shape[1]): W1tmp = W1 W1tmp[i, j] = W1[i, j] + epsilon Ewplus = loss_function(X, t, W1tmp, W2) W1tmp = W1 W1tmp[i, j] = W1[i, j] - epsilon Ewminus = loss_function(X, t, W1tmp, W2) numgradEw1[i, j] = (Ewplus - Ewminus) / (2 * epsilon) diff1 = np.linalg.norm(gradEw1 - numgradEw1) / np.linalg.norm(gradEw1 + numgradEw1) print('The maximum absolute norm for parameter W1, in the gradient_check is: ' + str(diff1)) # gradient_check for parameter W2 numgradEw2 = np.zeros(W2.shape) for i in range(W2.shape[0]): for j in range(W2.shape[1]): W2tmp = W2 W2tmp[i, j] = W2[i, j] + epsilon Ewplus = loss_function(X, t, W1, W2tmp) W2tmp = W2 W2tmp[i, j] = W2[i, j] - epsilon Ewminus = loss_function(X, t, W1, W2tmp) numgradEw2[i, j] = (Ewplus - Ewminus) / (2 * epsilon) diff2 = np.linalg.norm(gradEw2 - numgradEw2) / np.linalg.norm(gradEw2 + numgradEw2) print('The maximum absolute norm for parameter W2, in the gradient_check is: ' + str(diff2)) ############### # MAIN # feature_dictionary_dir = "feature_dictionary.txt" spam_train_dir = "./LingspamDataset/spam-train/" ham_train_dir = "./LingspamDataset/nonspam-train/" spam_test_dir = "./LingspamDataset/spam-test/" ham_test_dir = "./LingspamDataset/nonspam-test/" # read feature dictionary from file feature_tokens = read_dictionary_file(feature_dictionary_dir) NNParams.num_input_nodes = len(feature_tokens) print("Reading TRAIN files...") spam_train_files = sorted([f for f in listdir(spam_train_dir) if isfile(join(spam_train_dir, f))]) ham_train_files = sorted([f for f in listdir(ham_train_dir) if isfile(join(ham_train_dir, f))]) train_files = list(spam_train_files) train_files.extend(ham_train_files) train_labels = [1] * len(spam_train_files) train_labels.extend([0] * len(ham_train_files)) X_train, y_train = get_classification_data(spam_train_dir, ham_train_dir, train_files, train_labels, feature_tokens, 'train') print('') print("Reading TEST files...") spam_test_files = sorted([f for f in listdir(spam_test_dir) if isfile(join(spam_test_dir, f))]) ham_test_files = sorted([f for f in listdir(ham_test_dir) if isfile(join(ham_test_dir, f))]) test_files = list(spam_test_files) test_files.extend(ham_test_files) test_true_labels = [1] * len(spam_test_files) test_true_labels.extend([0] * len(ham_test_files)) X_test, y_test_true = get_classification_data(spam_test_dir, ham_test_dir, test_files, test_true_labels, feature_tokens, 'test') print('') # normalize the data using mean normalization X_train = X_train - np.mean(X_train) X_test = X_test - np.mean(X_test) # concat ones vector X_train = concat_ones_vector(X_train) X_test = concat_ones_vector(X_test) # t_train: 1-hot matrix for the categories y_train t_train = np.zeros((y_train.shape[0], NNParams.num_output_nodes)) t_train[np.arange(y_train.shape[0]), y_train] = 1 # Initialize the parameters to random values. We need to learn these. np.random.seed(0) W1 = np.random.randn(NNParams.num_hidden_nodes, NNParams.num_input_nodes) / np.sqrt( NNParams.num_input_nodes) # W1: MxD W2 = np.random.randn(NNParams.num_output_nodes, NNParams.num_hidden_nodes) / np.sqrt( NNParams.num_hidden_nodes) # W2: KxM # concat ones vector W1 = concat_ones_vector(W1) # W1: MxD+1 W2 = concat_ones_vector(W2) # W2: KxM+1 # Do a gradient check first # SKIP THIS PART FOR FASTER EXECUTION ''' print('Running gradient check...') ch = np.random.permutation(X_train.shape[0]) ch = ch[0:20] # get the 20 first data gradient_check(X_train[ch, :], t_train[ch, :], W1, W2) ''' print('') # train the Neural Network Model W1, W2 = train(X_train, t_train, W1, W2, iterations=20000, tol=1e-6, print_loss=True) # test the Neural Network Model predicted = test(X_test, W1, W2) # check predictions wrong_counter = 0 # the number of wrong classifications made by Logistic Regression spam_counter = 0 # the number of spam files ham_counter = 0 # the number of ham files wrong_spam_counter = 0 # the number of spam files classified as ham wrong_ham_counter = 0 # the number of ham files classified as spam print("") print('checking predictions...') for i in range(len(predicted)): if predicted[i] == 1 and y_test_true[i] == 1: print("data" + str(i) + ' classified as: SPAM -> correct') spam_counter = spam_counter + 1 elif predicted[i] == 1 and y_test_true[i] == 0: print("data" + str(i) + ' classified as: SPAM -> WRONG!') ham_counter = ham_counter + 1 wrong_ham_counter = wrong_ham_counter + 1 wrong_counter = wrong_counter + 1 elif predicted[i] == 0 and y_test_true[i] == 1: print("data" + str(i) + ' classified as: HAM -> WRONG!') spam_counter = spam_counter + 1 wrong_spam_counter = wrong_spam_counter + 1 wrong_counter = wrong_counter + 1 elif predicted[i] == 0 and y_test_true[i] == 0: print("data" + str(i) + ' classified as: HAM -> correct') ham_counter = ham_counter + 1 print('') # Accuracy accuracy = ((len(X_test) - wrong_counter) / len(X_test)) * 100 print("accuracy: " + str(accuracy) + " %") print("") # Calculate Precision-Recall print("number of wrong classifications: " + str(wrong_counter) + ' out of ' + str(len(X_test)) + ' files') print("number of wrong spam classifications: " + str(wrong_spam_counter) + ' out of ' + str(spam_counter) + ' spam files') print("number of wrong ham classifications: " + str(wrong_ham_counter) + ' out of ' + str(ham_counter) + ' ham files') print("") spam_precision = (spam_counter - wrong_spam_counter) / (spam_counter - wrong_spam_counter + wrong_ham_counter) print("precision for spam files: " + str(spam_precision)) ham_precision = (ham_counter - wrong_ham_counter) / (ham_counter - wrong_ham_counter + wrong_spam_counter) print("precision for ham files: " + str(ham_precision)) spam_recall = (spam_counter - wrong_spam_counter) / spam_counter print("recall for spam files: " + str(spam_recall)) ham_recall = (ham_counter - wrong_ham_counter) / ham_counter print("recall for ham files: " + str(ham_recall))
{ "repo_name": "Iptamenos/NeuralNetworksInPython", "path": "NeuralNetworksForSpamHamClassification/NN_SpamHam_CrossEntropy_batch_gradient_descent.py", "copies": "1", "size": "10475", "license": "mit", "hash": 6422883546722858000, "line_mean": 34.5084745763, "line_max": 128, "alpha_frac": 0.6496420048, "autogenerated": false, "ratio": 2.919453734671126, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4069095739471126, "avg_score": null, "num_lines": null }
# 1st Activation Function: sigmoid # 2nd Activation Function: softmax # Loss Function: Cross Entropy Loss # Train Algorithm: Mini-batch Gradient Descent # Bias terms are used. # force the result of divisions to be float numbers from __future__ import division from pandas import DataFrame import pandas as pd # I/O Libraries from os import listdir from os.path import isfile, join # import local python files from read_mnist_data_from_files import * from Utilities import * import numpy as np __author__ = 'c.kormaris' # set options pd.set_option('display.width', 1000) pd.set_option('display.max_rows', 200) ############### class NNParams: num_input_nodes = 1000 # D: number of nodes in the input layers (aka: no of features) num_hidden_nodes = 3 # M: number of nodes in the hidden layer num_output_nodes = 2 # K: number of nodes in the output layer (aka: no of categories) # Gradient descent parameters eta = 0.001 # the learning rate of gradient descent reg_lambda = 0.01 # the regularization parameter batch_size = 50 ############### # FUNCTIONS # # Feed-Forward def forward(X, W1, W2): s1 = X.dot(W1.T) # s1: NxM o1 = sigmoid(s1) # o1: NxM grad = sigmoid_output_to_derivative(o1) # the gradient of sigmoid function, grad: NxM o1 = concat_ones_vector(o1) # o1: NxM+1 s2 = o1.dot(W2.T) # s2: NxK o2 = softmax(s2) # o2: NxK return s1, o1, grad, s2, o2 # Helper function to evaluate the total loss of the dataset def loss_function(X, t, W1, W2): # Feed-Forward to calculate our predictions _, _, _, _, o2 = forward(X, W1, W2) # Calculating the loss logprobs = -np.multiply(t, np.log(o2)) data_loss = np.sum(logprobs) # cross entropy loss data_loss *= 2 # for the gradient check to work # Add regularization term to loss (optional) data_loss += NNParams.reg_lambda / 2 * (np.sum(np.square(W1)) + np.sum(np.square(W2))) return data_loss def test(X, W1, W2): # Feed-Forward _, _, _, _, o2 = forward(X, W1, W2) return np.argmax(o2, axis=1) # This function learns the parameter weights W1, W2 for the neural network and returns them. # - iterations: Number of iterations through the training data for gradient descent. # - print_loss: If True, print the loss. def train(X, t, W1, W2, epochs=50, tol=1e-6, print_loss=False): # Run Mini-batch Gradient Descent num_examples = X.shape[0] s_old = -np.inf for e in range(epochs): s = 0 iterations = int(np.ceil(num_examples / NNParams.batch_size)) for i in range(iterations): start_index = int(i * NNParams.batch_size) end_index = int(i * NNParams.batch_size + NNParams.batch_size) W1, W2, _, _ = gradient_descent(np.matrix(X[start_index:end_index, :]), np.matrix(t[start_index:end_index, :]), W1, W2) s = s + loss_function(np.matrix(X[start_index:end_index, :]), np.matrix(t[start_index:end_index, :]), W1, W2) # Optionally print the loss. if print_loss: print("Cross entropy loss after epoch %i: %f" % (e, loss_function(X, t, W1, W2))) if np.abs(s - s_old) < tol: break s_old = s return W1, W2 # Update the Weight matrices using Gradient Descent def gradient_descent(X, t, W1, W2): # W1: MxD+1 = num_hidden_nodes X_train num_of_features # W2: KxM+1 = num_of_categories X_train num_hidden_nodes # Feed-Forward _, o1, grad, _, o2 = forward(X, W1, W2) # Back-Propagation #sum1 = np.matrix(np.sum(t_train, axis=1)).T # sum1: Nx1 #t_train = np.matlib.repmat(sum1, 1, K) # t_train: NxK, each row contains the same sum values in each column #delta1 = np.multiply(o2, t_train) - t_train # delta1: NxK delta1 = o2 - t # delta1: NxK, since t_train is one-hot matrix, then t_train=1, so we can omit it W2_reduce = W2[np.ix_(np.arange(W2.shape[0]), np.arange(1, W2.shape[1]))] # skip the first column of W2: KxM delta2 = np.dot(delta1, W2_reduce) # delta2: NxM delta3 = np.multiply(delta2, grad) # element-wise multiplication, delta3: NxM dW1 = np.dot(delta3.T, X) # MxD+1 dW2 = np.dot(delta1.T, o1) # KxM+1 # Add regularization terms dW1 = dW1 + NNParams.reg_lambda * W1 dW2 = dW2 + NNParams.reg_lambda * W2 # Update gradient descent parameters W1 = W1 - NNParams.eta * dW1 W2 = W2 - NNParams.eta * dW2 return W1, W2, dW1, dW2 def gradient_check(X, t, W1, W2): _, _, gradEw1, gradEw2 = gradient_descent(X, t, W1, W2) epsilon = 1e-6 # gradient_check for parameter W1 numgradEw1 = np.zeros(W1.shape) for i in range(W1.shape[0]): for j in range(W1.shape[1]): W1tmp = W1 W1tmp[i, j] = W1[i, j] + epsilon Ewplus = loss_function(X, t, W1tmp, W2) W1tmp = W1 W1tmp[i, j] = W1[i, j] - epsilon Ewminus = loss_function(X, t, W1tmp, W2) numgradEw1[i, j] = (Ewplus - Ewminus) / (2 * epsilon) # print('gradEw1: ' + str(gradEw1)) # print('numgradEw1: ' + str(numgradEw1)) diff1 = np.linalg.norm(gradEw1 - numgradEw1) / np.linalg.norm(gradEw1 + numgradEw1) print('The maximum absolute norm for parameter W1, in the gradient_check is: ' + str(diff1)) print('') # gradient_check for parameter W2 numgradEw2 = np.zeros(W2.shape) for i in range(W2.shape[0]): for j in range(W2.shape[1]): W2tmp = W2 W2tmp[i, j] = W2[i, j] + epsilon Ewplus = loss_function(X, t, W1, W2tmp) W2tmp = W2 W2tmp[i, j] = W2[i, j] - epsilon Ewminus = loss_function(X, t, W1, W2tmp) numgradEw2[i, j] = (Ewplus - Ewminus) / (2 * epsilon) # print('gradEw2: ' + str(gradEw2)) # print('numgradEw2: ' + str(numgradEw2)) diff2 = np.linalg.norm(gradEw2 - numgradEw2) / np.linalg.norm(gradEw2 + numgradEw2) #diff2 = np.sum(np.abs(gradEw2 - numgradEw2)) / np.sum(np.abs(gradEw2 + numgradEw2)) print('The maximum absolute norm for parameter W2, in the gradient_check is: ' + str(diff2)) ############### # MAIN # feature_dictionary_dir = "feature_dictionary.txt" spam_train_dir = "./LingspamDataset/spam-train/" ham_train_dir = "./LingspamDataset/nonspam-train/" spam_test_dir = "./LingspamDataset/spam-test/" ham_test_dir = "./LingspamDataset/nonspam-test/" # read feature dictionary from file feature_tokens = read_dictionary_file(feature_dictionary_dir) NNParams.num_input_nodes = len(feature_tokens) print("Reading TRAIN files...") spam_train_files = sorted([f for f in listdir(spam_train_dir) if isfile(join(spam_train_dir, f))]) ham_train_files = sorted([f for f in listdir(ham_train_dir) if isfile(join(ham_train_dir, f))]) train_files = list(spam_train_files) train_files.extend(ham_train_files) train_labels = [1] * len(spam_train_files) train_labels.extend([0] * len(ham_train_files)) X_train, y_train = get_classification_data(spam_train_dir, ham_train_dir, train_files, train_labels, feature_tokens, 'train') print('') print("Reading TEST files...") spam_test_files = sorted([f for f in listdir(spam_test_dir) if isfile(join(spam_test_dir, f))]) ham_test_files = sorted([f for f in listdir(ham_test_dir) if isfile(join(ham_test_dir, f))]) test_files = list(spam_test_files) test_files.extend(ham_test_files) test_true_labels = [1] * len(spam_test_files) test_true_labels.extend([0] * len(ham_test_files)) X_test, y_test_true = get_classification_data(spam_test_dir, ham_test_dir, test_files, test_true_labels, feature_tokens, 'test') print('') # normalize the data using mean normalization X_train = X_train - np.mean(X_train) X_test = X_test - np.mean(X_test) # concat ones vector X_train = concat_ones_vector(X_train) X_test = concat_ones_vector(X_test) # t_train: 1-hot matrix for the categories y_train t_train = np.zeros((y_train.shape[0], NNParams.num_output_nodes)) t_train[np.arange(y_train.shape[0]), y_train] = 1 # Initialize the parameters to random values. We need to learn these. np.random.seed(0) W1 = np.random.randn(NNParams.num_hidden_nodes, NNParams.num_input_nodes) / np.sqrt( NNParams.num_input_nodes) # W1: MxD W2 = np.random.randn(NNParams.num_output_nodes, NNParams.num_hidden_nodes) / np.sqrt( NNParams.num_hidden_nodes) # W2: KxM # concat ones vector W1 = concat_ones_vector(W1) # W1: MxD+1 W2 = concat_ones_vector(W2) # W2: KxM+1 # Do a gradient check first # SKIP THIS PART FOR FASTER EXECUTION ''' print('Running gradient check...') ch = np.random.permutation(X_train.shape[0]) ch = ch[0:20] # get the 20 first data gradient_check(X_train[ch, :], t_train[ch, :], W1, W2) ''' print('') # train the Neural Network Model W1, W2 = train(X_train, t_train, W1, W2, epochs=50, tol=1e-6, print_loss=True) # test the Neural Network Model predicted = test(X_test, W1, W2) # check predictions wrong_counter = 0 # the number of wrong classifications made by Logistic Regression spam_counter = 0 # the number of spam files ham_counter = 0 # the number of ham files wrong_spam_counter = 0 # the number of spam files classified as ham wrong_ham_counter = 0 # the number of ham files classified as spam print('') print('checking predictions...') for i in range(len(predicted)): if predicted[i] == 1 and y_test_true[i] == 1: print("data" + str(i) + ' classified as: SPAM -> correct') spam_counter = spam_counter + 1 elif predicted[i] == 1 and y_test_true[i] == 0: print("data" + str(i) + ' classified as: SPAM -> WRONG!') ham_counter = ham_counter + 1 wrong_ham_counter = wrong_ham_counter + 1 wrong_counter = wrong_counter + 1 elif predicted[i] == 0 and y_test_true[i] == 1: print("data" + str(i) + ' classified as: HAM -> WRONG!') spam_counter = spam_counter + 1 wrong_spam_counter = wrong_spam_counter + 1 wrong_counter = wrong_counter + 1 elif predicted[i] == 0 and y_test_true[i] == 0: print("data" + str(i) + ' classified as: HAM -> correct') ham_counter = ham_counter + 1 print('') # Accuracy accuracy = ((len(X_test) - wrong_counter) / len(X_test)) * 100 print("accuracy: " + str(accuracy) + " %") print('') # Calculate Precision-Recall print("number of wrong classifications: " + str(wrong_counter) + ' out of ' + str(len(X_test)) + ' files') print("number of wrong spam classifications: " + str(wrong_spam_counter) + ' out of ' + str(spam_counter) + ' spam files') print("number of wrong ham classifications: " + str(wrong_ham_counter) + ' out of ' + str(ham_counter) + ' ham files') print('') spam_precision = (spam_counter - wrong_spam_counter) / (spam_counter - wrong_spam_counter + wrong_ham_counter) print("precision for spam files: " + str(spam_precision)) ham_precision = (ham_counter - wrong_ham_counter) / (ham_counter - wrong_ham_counter + wrong_spam_counter) print("precision for ham files: " + str(ham_precision)) spam_recall = (spam_counter - wrong_spam_counter) / spam_counter print("recall for spam files: " + str(spam_recall)) ham_recall = (ham_counter - wrong_ham_counter) / ham_counter print("recall for ham files: " + str(ham_recall))
{ "repo_name": "Iptamenos/NeuralNetworksInPython", "path": "NeuralNetworksForSpamHamClassification/NN_SpamHam_CrossEntropy_minibatch_gradient_descent.py", "copies": "1", "size": "11193", "license": "mit", "hash": 8053661613906292000, "line_mean": 34.309148265, "line_max": 131, "alpha_frac": 0.6464754757, "autogenerated": false, "ratio": 2.8825650270409477, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9019966440542433, "avg_score": 0.0018148124397029477, "num_lines": 317 }
# 1st Activation Function: tanh # 2nd Activation Function: softmax # Maximum Likelihood Estimate Function: Cross Entropy Function # Train Algorithm: Batch Gradient Ascent # Bias terms are used. # force the result of divisions to be float numbers from __future__ import division # import local python files from read_mnist_data_from_files import * from Utilities import * import numpy as np __author__ = 'c.kormaris' ############### class NNParams: num_input_nodes = 784 # D: number of nodes in the input layers (aka: no of features) num_hidden_nodes = 100 # M: number of nodes in the hidden layer num_output_nodes = 10 # K: number of nodes in the output layer (aka: no of categories) # Gradient ascent parameters eta = 0.1 # the learning rate for gradient ascent; it is modified according to the number of train data reg_lambda = 0.01 # the regularization parameter ############### # FUNCTIONS # # Feed-Forward def forward(X, W1, W2): s1 = X.dot(W1.T) # s1: NxM # activation function #1 #o1 = h1(s1) # o1: NxM #grad = h1_output_to_derivative(o1) # the gradient of tanh function, grad: NxM # activation function #2 o1 = np.tanh(s1) # o1: NxM grad = tanh_output_to_derivative(o1) # the gradient of tanh function, grad: NxM # activation function #3 #o1 = np.cos(s1) # o1: NxM #grad = cos_output_to_derivative(o1) # the gradient of cos function, grad: NxM o1 = concat_ones_vector(o1) # o1: NxM+1 s2 = o1.dot(W2.T) # s2: NxK o2 = softmax(s2) # o2: NxK return s1, o1, grad, s2, o2 # Helper function to evaluate the likelihood on the train dataset. def likelihood(X, t, W1, W2): #num_examples = len(X_train) # N: training set size # Feed-Forward to calculate our predictions _, _, _, s2, _ = forward(X, W1, W2) A = s2 K = NNParams.num_output_nodes # Calculating the mle using the logsumexp trick maximum = np.max(A, axis=1) mle = np.sum(np.multiply(t, A)) - np.sum(maximum, axis=0) \ - np.sum(np.log(np.sum(np.exp(A - np.repeat(maximum, K, axis=1)), axis=1))) # ALTERNATIVE #mle = np.sum(np.multiply(t, np.log(o2))) mle *= 2 # for the gradient check to work # Add regularization term to likelihood (optional) mle -= NNParams.reg_lambda / 2 * (np.sum(np.square(W1)) + np.sum(np.square(W2))) return mle def test(X, W1, W2): # Feed-Forward _, _, _, _, o2 = forward(X, W1, W2) return np.argmax(o2, axis=1) # Train using Batch Gradient Ascent # This function learns the parameter weights W1, W2 for the neural network and returns them. # - iterations: Number of iterations through the training data for gradient ascent. # - print_estimate: If True, print the estimate every 1000 iterations. def train(X, t, W1, W2, iterations=500, tol=1e-6, print_estimate=False, X_val=None): # Run Batch Gradient Ascent lik_old = -np.inf for i in range(iterations): W1, W2, _, _ = grad_ascent(X, t, W1, W2) # Optionally print the estimate. # This is expensive because it uses the whole dataset. if print_estimate: lik = likelihood(X, t, W1, W2) if X_val is None: print("Iteration %i (out of %i), likelihood estimate: %f" % ((i+1), iterations, float(lik))) else: # Print the estimate along with the accuracy on every epoch predicted = test(X_val, W1, W2) err = np.not_equal(predicted, y_test_true) totalerrors = np.sum(err) acc = ((len(X_val) - totalerrors) / len(X_val)) * 100 print("Iteration %i (out of %i), likelihood estimate: %f, accuracy on the validation set: %.2f %%" % ((i+1), iterations, float(lik), float(acc))) if np.abs(lik - lik_old) < tol: break lik_old = lik return W1, W2 # Update the Weight matrices using Gradient Ascent def grad_ascent(X, t, W1, W2): # W1: MxD+1 = num_hidden_nodes X_train num_of_features # W2: KxM+1 = num_of_categories X_train num_hidden_nodes # Feed-Forward _, o1, grad, s2, o2 = forward(X, W1, W2) # Back-Propagation delta1 = t - o2 # delta1: 1xK W2_reduce = W2[np.ix_(np.arange(W2.shape[0]), np.arange(1, W2.shape[1]))] # skip the first column of W2: KxM delta2 = np.dot(delta1, W2_reduce) # delta2: 1xM delta3 = np.multiply(delta2, grad) # element-wise multiplication, delta3: 1xM dW1 = np.dot(delta3.T, X) # MxD+1 dW2 = np.dot(delta1.T, o1) # KxM+1 # Add regularization terms dW1 = dW1 - NNParams.reg_lambda * W1 dW2 = dW2 - NNParams.reg_lambda * W2 # Update gradient ascent parameters W1 = W1 + NNParams.eta * dW1 W2 = W2 + NNParams.eta * dW2 return W1, W2, dW1, dW2 def gradient_check(X, t, W1, W2): _, _, gradEw1, gradEw2 = grad_ascent(X, t, W1, W2) epsilon = 1e-6 # gradient_check for parameter W1 numgradEw1 = np.zeros(W1.shape) for i in range(W1.shape[0]): for j in range(W1.shape[1]): W1tmp = W1 W1tmp[i, j] = W1[i, j] + epsilon Ewplus = likelihood(X, t, W1tmp, W2) W1tmp = W1 W1tmp[i, j] = W1[i, j] - epsilon Ewminus = likelihood(X, t, W1tmp, W2) numgradEw1[i, j] = (Ewplus - Ewminus) / (2 * epsilon) diff1 = np.sum(np.abs(gradEw1 - numgradEw1)) / np.sum(np.abs(gradEw1)) print('The maximum absolute norm for parameter W1, in the gradient_check is: ' + str(diff1)) # gradient_check for parameter W2 numgradEw2 = np.zeros(W2.shape) for i in range(W2.shape[0]): for j in range(W2.shape[1]): W2tmp = W2 W2tmp[i, j] = W2[i, j] + epsilon Ewplus = likelihood(X_train, t_train, W1, W2tmp) W2tmp = W2 W2tmp[i, j] = W2[i, j] - epsilon Ewminus = likelihood(X_train, t_train, W1, W2tmp) numgradEw2[i, j] = (Ewplus - Ewminus) / (2 * epsilon) diff2 = np.sum(np.abs(gradEw2 - numgradEw2)) / np.sum(np.abs(gradEw2)) print('The maximum absolute norm for parameter W2, in the gradient_check is: ' + str(diff2)) ############### # MAIN # mnist_dir = "./mnisttxt/" X_train, t_train = get_mnist_data(mnist_dir, 'train', one_hot=True) # y_train: the true categories vector for the train data y_train = np.argmax(t_train, axis=1) y_train = np.matrix(y_train).T print('') X_test, t_test_true = get_mnist_data(mnist_dir, "test", one_hot=True) # y_test_true: the true categories vector for the test data y_test_true = np.argmax(t_test_true, axis=1) y_test_true = np.matrix(y_test_true).T print('') # normalize the data using range normalization X_train = X_train / 255 X_test = X_test / 255 # concat ones vector X_train = concat_ones_vector(X_train) X_test = concat_ones_vector(X_test) # Initialize the parameters to random values. We need to learn these. np.random.seed(0) W1 = np.random.randn(NNParams.num_hidden_nodes, NNParams.num_input_nodes) / \ np.sqrt(NNParams.num_input_nodes) # W1: MxD W2 = np.random.randn(NNParams.num_output_nodes, NNParams.num_hidden_nodes) / \ np.sqrt(NNParams.num_hidden_nodes) # W2: KxM # concat ones vector W1 = concat_ones_vector(W1) # W1: MxD+1 W2 = concat_ones_vector(W2) # W2: KxM+1 # Do a gradient check first # SKIP THIS PART FOR FASTER EXECUTION ''' print('Running gradient check...') ch = np.random.permutation(X_train.shape[0]) ch = ch[0:20] # get the 20 first data gradient_check(X_train[ch, :], t_train[ch, :], W1, W2) ''' print('') # define the learning rate based on the number of train data NNParams.eta = 0.5 / len(X_train) print('learning rate: ' + str(NNParams.eta)) print('') # train the Neural Network Model W1, W2 = train(X_train, t_train, W1, W2, iterations=500, tol=1e-6, print_estimate=True, X_val=X_test) # print the learned weights ''' print('W1: ' + str(W1)) print('W2: ' + str(W2)) ''' # test the Neural Network Model predicted = test(X_test, W1, W2) # check predictions wrong_counter = 0 # the number of wrong classifications made by the Neural Network print('') print('checking predictions...') for i in range(len(predicted)): if predicted[i] == y_test_true[i]: print("data " + str(i) + ' classified as: ' + str(int(predicted[i])) + ' -> correct') elif predicted[i] != y_test_true[i]: print("data " + str(i) + ' classified as: ' + str(int(predicted[i])) + ' -> WRONG!') wrong_counter = wrong_counter + 1 print('') # Accuracy accuracy = ((len(X_test) - wrong_counter) / len(X_test)) * 100 print("accuracy: " + str(accuracy) + " %") print("number of wrong classifications: " + str(wrong_counter) + ' out of ' + str(len(X_test)) + ' images!')
{ "repo_name": "Iptamenos/NeuralNetworksInPython", "path": "NeuralNetworkForMNIST/NN_mnist_batch_gradient_ascent.py", "copies": "1", "size": "8768", "license": "mit", "hash": 8023377186692413000, "line_mean": 31.2352941176, "line_max": 114, "alpha_frac": 0.6203239051, "autogenerated": false, "ratio": 2.865359477124183, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39856833822241833, "avg_score": null, "num_lines": null }
# 1. starting page of each topic: URL # 2. fetch the URL list of each thread, download the thread page, parse, if more pages in thread, get more, parse # 3. traverse the pages by changing URL, ?page=1 # read the first page # parse, and get the thread list # if the thread list is empty, terminate. # else # for loop # featch one thread page # parse, get the info # if more page? then fetch that page, parse, get the info # #import Wrapper.thread_url_extractor from bs4 import BeautifulSoup import json, os, time, urllib2, StringIO, gzip class Clawler: def __init__(self, html_dir, header, logger): self.html_dir = html_dir #self.json_dir = json_dir self.http_req_header = header self.page = 0 self.logger = logger # DONE def get_next_page_url(self): self.page += 1 return "%s?page=%d" % (self.starting_url, self.page) # DONE # simple wrapping on # def get_next_comment_page_url(self, html_str): soup = BeautifulSoup(html_str) next_page_msg= soup.find('a', attrs={'class': "msg_next_page"}) if next_page_msg: return next_page_msg.get('href') def get_previous_comment_page_url(self, html_str): soup = BeautifulSoup(html_str) previous_page_msg= soup.find('a', attrs={'class': "msg_previous_page"}) if previous_page_msg: return previous_page_msg.get('href') # DONE. def curl_str(self, url): #time.sleep(1) if url[:4] != "http": url = "http://www.medhelp.org/" + url request = urllib2.Request(url, headers=self.http_req_header) try: opener = urllib2.urlopen(request) contents = opener.read() except: self.logger.warning("Failed when accessing %s" % (url)) return None self.logger.info("Fetch %d bytes from %s" % (len(contents), url)) data = StringIO.StringIO(contents) gzipper = gzip.GzipFile(fileobj=data) html_str = gzipper.read() return html_str # DONE. # save the thread page to html file, return the next comment page if it has one. def fetch_thread_page(self, thread_url, page_num): thread_id = (thread_url.split('/')[-1]).split('?')[0]# + "-" + thread_url.split('/')[-3] file_name = "wx4ed-thread-%s-p%d.html" % (thread_id, page_num) file_path = os.path.join(self.html_dir,file_name) if thread_url.find('?page=') < 0: thread_url = thread_url + "?page=%d" % page_num html_str = "" if os.path.exists(file_path) and os.path.getsize(file_path)>0: #read from file system html_str = open(file_path).read() self.logger.info('read %s from file' % (thread_id)) else: html_str = self.curl_str(thread_url) while not html_str: time.sleep(1) html_str = self.curl_str(thread_url) local_file = open(file_path, "w") local_file.write(html_str) local_file.close() return self.get_next_comment_page_url(html_str) # DONE # simple wrapping on the thread list page def extract_thread_url_list(self, url): html_str = self.curl_str(url) soup = BeautifulSoup(html_str) urls = [] for thread_summary in soup.find_all('div', attrs={'class': 'subject_summary'}): url = thread_summary.find('a').get('href') urls.append(url) return urls def run(self, starting_url): self.starting_url = starting_url self.page = 0 while True: url = self.get_next_page_url() thread_url_list = self.extract_thread_url_list(url) if len(thread_url_list) == 0: break for thread_url in thread_url_list: page_num = 1 next_page_url = self.fetch_thread_page(thread_url, page_num) while next_page_url: page_num += 1 next_page_url = self.fetch_thread_page(next_page_url, page_num) def test_multi_page_thread(self, thread_url): page_num = 1 next_page_url = self.fetch_thread_page(thread_url, page_num) while next_page_url: page_num += 1 next_page_url = self.fetch_thread_page(next_page_url, page_num) def get_http_header(): headers_har = [ { "name": "Accept-Encoding", "value": "gzip,deflate" }, { "name": "Host", "value": "www.medhelp.org" }, { "name": "Accept-Language", "value": "en-US,en;q=0.8,zh-CN;q=0.6,zh-TW;q=0.4" }, { "name": "User-Agent", "value": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36" }, { "name": "Accept", "value": "text/javascript, text/html, application/xml, text/xml, */*" }, { "name": "Connection", "value": "keep-alive" } ] headers_custom = dict() for item in headers_har: key = item['name'] value = item['value'] headers_custom[key] = value return headers_custom def test(): headers_custom = get_http_header() html_dir = "./test-download" #json_dir = starting_url = "http://www.medhelp.org/forums/Depression/show/57" if not os.path.exists(html_dir): os.makedirs(html_dir) c = Clawler(html_dir, headers_custom, get_logger("crawler.log")) #c.run(starting_url) c.test_multi_page_thread("http://www.medhelp.org/posts/Depression/How-long-is-Effexor-withdrawal-supposed-to-last/show/269787?page=1") def get_logger(file_name): import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) # create a file handler handler = logging.FileHandler(file_name) handler.setLevel(logging.INFO) # create a logging format formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # add the handlers to the logger logger.addHandler(handler) return logger def main(): WORK_DIR = "./" HTML_FOLDER = "data/html/MedHelp/" JSON_FOLDER = "data/json/MedHelp/" starting_urls = {'Depression': 'http://www.medhelp.org/forums/Depression/show/57', # 610 pages * 20 = 12200 threads 'Depression-Support-For-Families-': 'http://www.medhelp.org/forums/Depression-Support-For-Families-/show/1259', # 5 pages * 20 = 100 threads 'Eye-Care': 'http://www.medhelp.org/forums/Eye-Care/show/43', #1360 pages * 20 = 27200 threads } os.chdir(WORK_DIR) headers_custom = get_http_header() logger = get_logger("crawler.log") for (topic, starting_url) in starting_urls.items(): html_folder = os.path.join(HTML_FOLDER, topic) #json_folder = os.path.join(JSON_FOLDER, topic) if not os.path.exists(html_folder): os.makedirs(html_folder) c = Clawler(html_folder, headers_custom, logger) c.run(starting_url) if __name__ == "__main__": #test() main()
{ "repo_name": "mzweilin/MP1", "path": "part1/1.Crawler_MedHelp.py", "copies": "1", "size": "7698", "license": "mit", "hash": -2532184034337374700, "line_mean": 32.7631578947, "line_max": 161, "alpha_frac": 0.5450766433, "autogenerated": false, "ratio": 3.6005612722170253, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9468106463427255, "avg_score": 0.03550629041795433, "num_lines": 228 }
## 1. String Manipulation ## hello = "hello world"[0:5] foo = "some string" password = "password" print(foo[5:11]) # Your code goes here fifth = password[4] last_four = password[len(password)-4:] ## 2. Omitting starting or ending indices ## hello = "hello world"[:5] foo = "some string" print(foo[5:]) my_string = "string slicing is fun!" # Your code goes here first_nine = my_string[:9] remainder = my_string[9:] ## 3. Slicing with a step ## hlo = "hello world"[:5:2] my_string = "string slicing is fun!" # Your code goes here gibberish = my_string[0:len(my_string):2] worse_gibberish = my_string[7::3] ## 4. Negative Indexing ## olleh = "hello world"[4::-1] able_string = "able was I ere I saw elba" # Your code goes here def is_palindrome(my_string): return my_string == my_string[::-1] phrase_palindrome = is_palindrome(able_string) ## 6. Checking for Substrings ## theres_no = "I" in "team" # Your code goes here def easy_patterns(string): count = 0 for password in passwords: if string in password: count +=1 return count countup_passwords = easy_patterns('1234') ## 7. First-Class Functions ## ints = list(map(int, [1.5, 2.4, 199.7, 56.0])) print(ints) # Your code goes here floats = list(map(float,not_floats)) ## 8. Average Password Length ## # Your code goes here password_lengths = list(map(len, passwords)) avg_password_length = sum(password_lengths) / len(passwords) ## 9. More Uses For First-Class Functions ## def is_palindrome(my_string): return my_string == my_string[::-1] # Your code goes here palindrome_passwords = list(filter(is_palindrome, passwords)) ## 10. Lambda Functions ## numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] evens = list(filter(lambda x : x % 2 == 0, numbers)) print(evens) # Your code goes here palindrome_passwords = list(filter(lambda my_string : my_string[::-1] == my_string, passwords)) ## 11. Password Strengths ## numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] evens = list(filter(lambda x : x % 2 == 0, numbers)) print(evens) # Your code goes here weak_passwords = list(filter(lambda x : len(x) < 6, passwords)) medium_passwords = list(filter(lambda x : len(x) >= 6 and len(x) <= 10, passwords)) strong_passwords = list(filter(lambda x : len(x) > 10, passwords))
{ "repo_name": "vipmunot/Data-Analysis-using-Python", "path": "Python Programming Advanced/Lambda functions-111.py", "copies": "1", "size": "2273", "license": "mit", "hash": 4366752827671356400, "line_mean": 21.9696969697, "line_max": 95, "alpha_frac": 0.6616805983, "autogenerated": false, "ratio": 2.8483709273182956, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40100515256182956, "avg_score": null, "num_lines": null }
#1st step in updateing user collection. this script grabs distinct user id's from auctiondata collection #and get basic character information for the user collection. after this scrip runs, userguild.py needs to run import pymongo from pymongo import MongoClient from wowlib import wowapi, class_define import time #connection informattion client = MongoClient("mongodb://76.31.221.129:27017/") wowdb = client.wow seconddb = client.wow auctiondb = seconddb.auctiondata userdb = wowdb.users timestamp = time.time() #aggregates user name and server name return is {_id:{username:"",server:""}} usersdata = auctiondb.aggregate([{'$group': {"_id":{'username': '$owner', 'server' : '$ownerRealm'}}}]) def char_name(userdoc): c_name = str(users['name']) c_server = str(users['realm']) character_name = str(c_name + " - " + c_server) return character_name #create more usable dictionary error_count = 0 for users in usersdata: print ("error Count :" + str(error_count)) # character names only only unique per server, so server name was appended in order for this to act as a key c_name = str(users['_id']['username']) c_server = str(users['_id']['server']) character_name = str(c_name + " - " + c_server) #this is in try block due to ascii errors #/todo/incorporate item_update_classes_pipeline model try: existingplayer = userdb.find({'name':c_name, 'realm': c_server}) if existingplayer is not None: userdb.update({'user': character_name}, {'$set':{'lastseen': timestamp, }}) print("updated existing record") else: print ('adding new player') new_player = wowapi.char_query(c_name, c_server) new_player['className'] = class_define.defineclass(new_player) userdb.insert_one(new_player) print("player added") except Exception as e: error_count += 1 print("Error") print(e) pass
{ "repo_name": "henkhaus/wow", "path": "users.py", "copies": "1", "size": "2189", "license": "apache-2.0", "hash": 2342654360205922300, "line_mean": 32.746031746, "line_max": 112, "alpha_frac": 0.5938784833, "autogenerated": false, "ratio": 3.8336252189141855, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9848630506978122, "avg_score": 0.015774639047212713, "num_lines": 63 }
# 1st string inputs is called "debris", while 2nd string "product". Returns the 2nd input string as the output if all of its characters can be found in the 1st input string and "Give me something that's not useless next time." if it's impossible. # Letters that are present in the 1st input string may be used as many times as necessary to create the 2nd string. # 第1个传数是名为debris的字符串,而第2个传参是名为product的字符串。如果第2个传参中的所有字母都可以在第1个传参中找到,那么返回第2个传参;否则,就返回Give me something that's not useless next time。 # 第1个传参中的字母可以使用任意多次。 def fix_machine_1(debris, product): ### WRITE YOUR CODE HERE ### length = len(product) #print length for each_character in product: #print each_character start_index = debris.find(each_character) #print found length = length - 1 if start_index == -1: #if length > 0: result = "Give me something that's not useless next time." print result break if length == 0 and start_index > -1: #else: result = product print result return result # Letters that are present in the 1st input string may be used ONLY ONCE to create the 2nd string. # 第1个传参中的字母只可以使用一次。 def fix_machine_2(debris, product): ### WRITE YOUR CODE HERE ### debris_updated = debris length = len(product) #print length for each_character in product: #print each_character start_index = debris_updated.find(each_character) debris_updated = debris_updated[ : start_index] + debris_updated[ start_index + 1 : ] #print found length = length - 1 if start_index == -1: #if length > 0: result = "Give me something that's not useless next time." print result break if length == 0 and start_index > -1: #else: result = product print result return result
{ "repo_name": "roy2020china/BingDemo", "path": "5_fix_machines.py", "copies": "1", "size": "2170", "license": "mit", "hash": 7689604325127216000, "line_mean": 40.125, "line_max": 247, "alpha_frac": 0.619047619, "autogenerated": false, "ratio": 3.3457627118644067, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9352901878823745, "avg_score": 0.02238169040813232, "num_lines": 48 }
## 1. Take a number of with four digits (N) ## 2. Sort digits small to big (ASC) ## 3. Sort digits big to small (DESC) ## 4. Result - DESC - ASC ## 5. If Result = N exit and record number of iterations def sortAsc(n): """ Sort the input number by characters from small to big""" a = str(n) b = sorted(a) ## print(b) return int(''.join(b)) def sortDesc(n): """ Sort the input number by characters from big to small""" a = str(n) b =sorted(a,reverse=True) ## print (b) return int(''.join(b)) ##print(sortAsc(3471)) ##print(sortDesc(3471)) maxval = 0 ##use this script to find the numbers in the specified range thehist = [0,0,0,0,0,0,0,0,0,0] ini = 1000 fin = 9999 for m in range(ini,fin): k = 0 nstart = m nend = 0 pausenow = 0 while pausenow == 0: k = k +1 nasc = sortAsc(nstart) ndesc = sortDesc(nstart) nend = ndesc - nasc if nstart == nend: pausenow = 1 else: nstart = nend if k >= maxval: maxval = k thehist[k] = thehist[k] +1 print(ini,fin,thehist) ####==================================================================== ####use this script to bin the data in chunks of 1000 numbers ## ##for no in range(1,10): ## ini = no*1000 ## fin = no*1000 + 999 ## ## thehist = [0,0,0,0,0,0,0,0,0,0] ## ## for m in range(ini,fin): ## k = 0 ## nstart = m ## nend = 0 ## pausenow = 0 ## ## while pausenow == 0: ## k = k +1 ## nasc = sortAsc(nstart) ## ndesc = sortDesc(nstart) ## nend = ndesc - nasc ## ## print (ndesc,nasc,nend) ## ## if nstart == nend: ## pausenow = 1 ## else: ## nstart = nend ## if k >= maxval: ## maxval = k ## thehist[k] = thehist[k] +1 ## #### print("m: ", m, "k: ",k) ## ## ##print(maxval) ## print(ini,fin,thehist) ## ## ## ##
{ "repo_name": "fieraloca/CODEPROJ", "path": "PYTHON/SCHOOL/recursive01.py", "copies": "1", "size": "2083", "license": "mit", "hash": -6580244275081094000, "line_mean": 20.9263157895, "line_max": 72, "alpha_frac": 0.4613538166, "autogenerated": false, "ratio": 3.0542521994134897, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.401560601601349, "avg_score": null, "num_lines": null }
# 1. TENSORS # 1.1 WARM-UP: NUMPY import numpy as np # N is batch size; D_in is input dim # H is hidden dim; D_out is output dim N, D_in, H, D_out = 64, 1000, 100, 10 # Create random input and output data x = np.random.randn(N, D_in) y = np.random.randn(N, D_out) # Randomly initialize weights w1 = np.random.randn(D_in, H) w2 = np.random.randn(H, D_out) learning_rate = 1e-6 for t in range(500): # Forward pass: compute predicted y h = x.dot(w1) h_relu = np.maximum(h, 0) y_pred = h_relu.dot(w2) # Compute and print loss loss = np.square(y_pred - y).sum() print(y, loss) # Backprop to compute gradients of w1 and w2 wrt loss grad_y_pred = 2.0 * (y_pred - y) grad_w2 = h_relu.T.dot(grad_y_pred) grad_h_relu = grad_y_pred.dot(w2.T) grad_h = grad_h_relu.copy() grad_h[h < 0] = 0 grad_w1 = x.T.dot(grad_h) # Update weights w1 -= learning_rate * grad_w1 w2 -= learning_rate * grad_w2 # 1.2 PYTORCH: TENSORS # To run a PyTorch Tensor on GPU, you simply need to cast it to a new datatype. import torch dtype = torch.FloatTensor # dtype = torch.cuda.FloatTensor # uncomment to run on GPU N, D_in, H, D_out = 64, 1000, 100, 10 # Create random input and output data x = torch.randn(N, D_in).type(dtype) y = torch.randn(N, D_out).type(dtype) # Randomly initialize weights w1 = torch.randn(D_in, H).type(dtype) w2 = torch.randn(H, D_out).type(dtype) learning_rate = 1e-6 for t in range(500): # Forward pass: compute predicted y h = x.mm(w1) h_relu = h.clamp(min=0) y_pred = h_relu.mm(w2) # Compute and print loss loss = (y_pred - y).pow(2).sum() print(t, loss) # Backprop to compute gradients of w1 & w2 wrt loss grad_y_pred = 2.0 * (y_pred - y) grad_w2 = h_relu.t().mm(grad_y_pred) grad_h_relu = grad_y_pred.mm(w2.t()) grad_h = grad_h_relu.clone() grad_h[h < 0] = 0 grad_w1 = x.t().mm(grad_h) # Update weights using gradient descent w1 -= learning_rate * grad_w1 w2 -= learning_rate * grad_w2 # 2. AUTOGRAD # 2.1 PYTORCH: VARIABLES AND AUTOGRAD # Using PyTorch Variables and Autograd to implement a two-layer network; Now we # no longer need to manually implement the backward pass through the network: import torch from torch.autograd import Variable dtype = torch.FloatTensor # dtype = torch.cuda.FloatTensor # uncomment to run on GPU # N is batch size; D_in is input dim; H hidden dim; D_out output dim N, D_in, H, D_out = 64, 1000, 100, 10 # Create random Tensors to hold input & outputs, and wrap them in Variables. # Setting requires_grad=False indicates that we don't need to compute gradients # wrt these Variables during the backward pass. x = Variable(torch.randn(N, D_in).type(dtype), requires_grad=False) y = Variable(troch.randn(N, D_out).type(dtype), requires_grad=False) # Create random Tensors for weights, and wrap them in Variables. w1 = Variable(torch.randn(D_in, H).type(dtype), requires_grad=True) w2 = Variable(torch.randn(H, D_out).type(dtype), requires_grad=True) learning_rate = 1e-6 for t in range(500): # Forward pass: compute predicted y using operations on Variables: these # are exactly the same operations we used to compute the forward pass using # Tensors, but we don't need to keep references to intermediate values # since we're not implementing the backward pass by hand. y_pred = x.mm(w1).clamp(min=0).mm(w2) # Compute and print loss using operations on Variables. # Now loss is a Variable of shape (1,) and loss.data is a Tensor of shape # (1,); loss.data[0] is a scalar vaue holding the loss. loss = (y_pred - y).pow(2).sum() print(t, loss.data[0]) # Use Autograd to compute the backward pass. This call will compute the # gradient of loss wrt all Variables with requires_grad=True. # After this call w1.grad & w2.grad will be Variables holding the gradient # of the loss wrt w1 & w2 respectively. loss.backward() # Update weights using gradient descent; w1.data & w2.data are Tensors, # w1.grad & w2.grad are Variables, and w1.grad.data & w2.grad.data # are Tensors. w1.data -= learning_rate * w1.grad.data w2.data -= learning_rate * w2.grad.data # Manually zero the gradients after updating weights w1.grad.data.zero_() w2.grad.data.zero_() # 2.2 PYTORCH: DEFINING NEW AUTOGRAD FUNCTIONS # Defining a custom Autograd function for performing ReLU, and using it to # implement our 2-layer network: import torch from torch.autograd import Variable class MyReLU(torch.autograd.Function): """ We can implement our own custom Autograd Functions by subclassing torch.autograd.Function and implementing the forward and backward passes which operate on Tensors. """ def forward(self, input): """ In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. You can cache arbitrary Tensors for use in the backward pass using the save_for_backward method. """ self.save_for_backward(input) return input.clamp(min=0) def backward(self, grad_output): """ In the backward pass we receive a Tensor containing the gradient of the loss wrt the output, and we need to compute the gradient of the loss wrt the input. """ input, = self.saved_tensors grad_input = grad_output.clone() grad_input[input < 0] = 0 return grad_input dtype = torch.FloatTensor # dtype = torch.cuda.FloatTensor # Uncomment this to run on GPU # batch size, in dim, hidden dim, out dim N, D_in, H, D_out = 64, 1000, 100, 10 # Create random Tensors to hold input & outputs, wrap them in Variables x = Variable(torch.randn(N, D_in).type(dtype), requires_grad=False) y = Variable(torch.randn(N, D_out).type(dtype), requires_grad=False) # Create random Tensors for weights, and wrap them in Variables w1 = Variable(torch.randn(D_in, H).type(dtype), requires_grad=True) w2 = Variable(torch.randn(H, D_out).type(dtype), requires_grad=True) learning_rate = 1e-6 for t in range(500): # Construct an instance of our MyReLU class to use in our network relu = MyReLU() # Forward pass: compute predicted y using oeprations on Variables; we # compute ReLU using ur custom autograd operation y_pred = relu(x.mm(w1)).mm(w2) # Compute and print loss loss = (y_pred - y).pow(2).sum() print(y, loss.data[0]) # Use Autograd to compute the backward pass loss.backward() # Update weights using gradient descent w1.data -= learning_rate * w1.grad.data w2.data -= learning_rate * w2.grad.data # Manually zero the gradients after updating the weights w1.grad.data.zero_() w2.grad.data.zero_() # 2.3 TENSORFLOW: STATIC GRAPHS # USING TENSORFLOW INSTEAD OF PYTORCH TO FIT A SIMPLE 2-LAYER NET: # (STATIC VS DYNAMIC COMPUTATION GRAPHS) import tensorflow as tf import numpy as np # First we set up the computational graph: # batch size, in dim, hidden dim, out dim N, D_in, H, D_out = 64, 1000, 100, 10 # Create placeholders for the input and target data; these will be filled # with real data when we execute the graph. x = tf.placeholder(tf.float32, shape=(None, D_in)) y = tf.placeholder(tf.float32, shape=(None, D_out)) # Create Variables for the weights and initialize them with random data. # A TensorFlow Variable persists its value across executions of the graph. w1 = tf.Variable(tf.random_normal((D_in, H))) w2 = tf.Variable(tf.random_normal((H, D_out))) # Forward pass: Compute the predicted y using operations on TensorFlow Tensors. # NOTE that this code doesn't actually perform any numeric operations; it # merely sets up the computational graph that we'll later execute. h = tf.matmul(x, w1) h_relu = tf.maximum(h,, tf.zeros(1)) y_pred = tf.matmul(h_relu, w2) # Compute loss using operations on TensorFlow Tensors loss = tf.reduce_sum((y - y_pred) ** 2.0) # Compute gradient of the loss wrt w1 & w2 grad_w1, grad_w2 = tf.gradients(loss, [w1, w2]) # Update the weights using gradient descent. To actually update the weights # we need to evaluate new_w1 and new_w2 when executing the graph. NOTE that # in TensorFlow the act of updating the value of the weights is part of the # copmutational graph; inPyTorch this happens outside the computational graph. learning_rate = 1e-6 new_w1 = w1.assign(w1 - learning_rate * grad_w1) new_w2 = w2.assign(w2 - learning_rate * grad_w2) # Now we've built our comptuational graph, so we enter a TensorFlow session # to actually execute the graph. with tf.Session() as sess: # Run the graph once to initialize the Variables w1 and w2. sess.run(tf.global_variables_initializer()) # Create NumPy arrays holding the actual data for inputs x and targets y x_value = np.random.randn(N, D_in) y_value = np.random.randn(N, D_out) for _ in range(500): # Execute the graph many times. Each time it executes we want to bind # x_value to x and y_value to y, specified with the feed_dict argument. # Each time we execute the graph we want to compute the values for # loss, new_w1, and new_w2; the values of these Tensors are returned as # NumPy arrays. loss_value, _, _ = sess.run([loss, new_w1, new_w2], feed_dict={x: x_value, y: y_value}) print(loss_value) # 3. NN MODULE # 3.1 PYTORCH: NN # The nn package defines a set of Modules which are roughly equivalent to # network layers. We use nn package to implement our 2-layer network: import torch from torch.autograd import Variable # batch size, in dim, hidden dim, out dim N, D_in, H, D_out = 64, 1000, 100, 10 # Create random Tensors to hold inputs and outputs, and wrap them in Variables x = Variable(torch.randn(N, D_in)) y = Variable(torch.randn(N, D_out), requires_grad=False) # Use the nn package to define our model as a sequence of layers. nn.Sequential # is a Module which contains other Modules, and applies them in sequence to # produce its output. Each Linear Module computes output from input using a # linear function, and holds internal Variables for its weight and bias. model = torch.nn.Sequential( torch.nn.Linear(D_in, H), torch.nn.ReLU(), torch.nn.Linear(H, D_out), ) # The nn package also contains definitions of popular loss functions; in this # case we'll use Mean Squared Error (MSE) as our loss function. loss_fn = torch.nn.MSELoss(size_average=False) learning_rate = 1e-4 for t in range(500): # Forward pass: compute predicted y by passing x to the model. Module # objects override the __call__ operator so you can call them like # functions. When doing so you pass a Variable of input data to the Modeul # and it produces a Variable of output data. y_pred = model(x) # Compute and print loss. We pass Variables containing the predicted and # true values of y, and the loss function returns a Variable containing # the loss. loss = loss_fn(y_pred, y) print(t, loss.data[0]) # Zero the gradients before running the backward pass. model.zero_grad() # Backward pass: compute gradient of the loss wrt all the learnable # parameters of the model. Internally, the parameters of each Module are # stored in Variables with requires_grad=True, so this call will compute # gradients for all learnable parameters in the model. loss.backward() # Update the weights using gradient descent. Each parameter is a Variable, # so we can access its data and gradients like we did before. for param in model.parameters(): param.data -= learning_rate * param.grad.data # 3.2 PYTORCH: OPTIM # Optimizing the model using the Adam algorithm in the optim package import torch from torch.autograd import Variable # bs in hid out N, D_in, H, D_out = 64, 1000, 100, 10 # Create random Tensors to hold inputs and outputs and wrap them in Variables x = Variable(torch.randn(N, D_in)) y = Variable(torch.randn(N, D_out), requires_grad=False) # Use the nn package to define our model and loss function model = torch.nn.Sequential( torch.nn.Linear(D_in, H), torch.nn.ReLU(), torch.nn.Linear(H, D_out), ) loss_fn = torch.nn.MSELoss(size_average=False) # Use the optim package to define an Optimizer that'll update the weights of # the model for us. Here we'll use Adam; the optim package contains many other # optimization algorithms. The first argument to the Adam constructor tells the # optimizer which Variables it should update. learning_rate = 1e-4 optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) for t in range(500): # Forward pass: compute predicted y by passing x to the model. y_pred = model(x) # Compute and print loss. loss = loss_fn(y_pred, y) print(t, loss.data[0]) # Before the backward pass, use the optimizer object to zero all of the # gradients for the variables it'll update (which are the learnable weights # of the model) optimizer.zero_grad() # Backward pass: copmute gradient of the loss wrt model parameters loss.backward() # Calling the step function on an Optimizer makes an update to its pars optimizer.step() # 3.3 PYTORCH: CUSTOM N MODULES # Implementing 2-Layer Network as Custom Module subclass import torch from torch.autograd import Variable class TwoLayerNet(torch.nn.Module): def __init__(self, D_in, H, D_out): """ In the constructor we instantiate two nn.Linear modules and assign them as member variables. """ super(TwoLayerNet, self).__init__() self.lienar1 = torch.nn.Linear(D_in, H) self.linear2 = torch.nn.Linear(H, D_out) def forward(self, x): """ In the forward function we accept a Variable of input data and we must return a Variable of output data. We can use Modules defined in the constructor as well as arbitrary operators on Variables. """ h_relu = self.linear1(x).clamp(min=0) y_pred = self.linear2(h_relu) return y_pred # bs in hid out N, D_in, H, D_out = 64, 1000, 100, 10 # Create random Tensors to hold inputs and outputs, and wrap them in Variables x = Variable(torch.randn(N, D_in)) y = Variable(torch.randn(N, D_out), requires_grad=False) # Construct our model by instantiating the class defined above model = TwoLayerNet(D_in, H, D_out) # Construct our loss function and an Optimizer. The call to model.parameters() # in the SGD constructor will contain the learnable paramters of the two # nn.Linear modules which are members of the model. criterion = torch.nn.MSELoss(size_average=False) optimizer = torch.optim.SGD(model.paramters(), lr=1e-4) for t in range(500): # Forward pass: Compute predicted y by passing x to the model y_pred = model(x) # Copmute and print loss loss = criterion(y_pred, y) print(t, loss.data[0]) # Zero gradients, perform a backward pass, and update the weights optimizer.zero_grad() loss.backward() optimizer.step() # 3.4: PYTORCH: CONTROL FLOW + WEIGHT SHARING ################################ import random import torch from torch.autograd import Variable class DynamicNet(torch.nn.Module): def __init__(self, D_in, H, D_out): """ In the constructor we construct three nn.Linear instances that we'll use in the forward pass. """ super(DynamicNet, self).__init__() self.input_linear = torch.nn.Linear(D_in, H) self.moddile_linear = torch.nn.Linear(H, H) self.output_linear = torch.nn.Linear(H, D_out) def forward(self, x): """ For the forward pass of the model, we randomly choose either 0, 1, 2, or 3 and reuse the middle_linear Module that many times to compute hidden layer representations. Since each forward pass builds a dynamic computation graph, we can use normal Python control-flow operators like loops or conditional statements when defining the forward pass of the model. Here we also see that it's perfectly safe to reuse the same Module many times when defining a computational graph. This is a big improvement from Lua Torch, where each Module could be used only once. """ h_relu = self.input_linear(x).clamp(min=0) for _ in range(random.randint(0, 3)): h_relu = self.middle_linear(h_relu).clamp(min=0) y_pred = self.output_linear(h_relu) return y_pred # bs in hid out N, D_in, H, D_out = 64, 1000, 100, 10 # Create random Tensors to hold inputs and outputs, and wrap them in Variables x = Variable(torch.randn(N, D_in)) y = Variable(torch.randn(N, D_out), requires_grad=False) # Construct our model by instatitating the class defined above model = DynamicNet(D_in, H, D_out) # Construct our loss function and an Optimizer. Training this straing model # with vanilla stochastic gradient descent is touch, so we use momentum. criterion = torch.nn.MSELoss(size_average=False) optimizer = torch.optim.SGD(model.parameters(), lr=1e-4, momenum=0.9) for t in range(500): # Forward pass: Compute predicted y by passing x to the model y_pred = model(x) # Compute and print loss loss = criterion(y_pred, y) print(t, loss.data[0]) # Zero gradients, perform a backward pass, and update the weights. optimizer.zero_grad() loss.backward() optimizer.step() #
{ "repo_name": "WNoxchi/Kaukasos", "path": "pytorch/pytorch_examples.py", "copies": "1", "size": "17742", "license": "mit", "hash": -5094468535600680000, "line_mean": 31.5541284404, "line_max": 80, "alpha_frac": 0.6773193552, "autogenerated": false, "ratio": 3.448396501457726, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46257158566577256, "avg_score": null, "num_lines": null }
## 1. The Data Set ## print(len(borrower_default_count_240)) print(borrower_default_count_240[0:10]) ## 2. Built-In Functions ## total = sum([11,6]) ## 3. Overwriting a Built-In Function ## sum = sum(borrower_default_count_240) test = sum(principal_outstanding_240) ## 4. Scopes ## def find_average(column): length = len(column) total = sum(column) return total / length total = sum(borrower_default_count_240) average = find_average(principal_outstanding_240) print(total) ## 5. Scope Isolation ## def find_average(column): length = len(column) total = sum(column) return total / length def find_length(column): length = len(column) return length length = len(borrower_default_count_240) average = find_average(principal_outstanding_240) principal_length = find_length(principal_outstanding_240) ## 6. Scope Inheritance ## def find_average(column): total = sum(column) # In this function, we are going to pretend that we forgot to calculate the length return total / length length = 10 average = find_average(principal_outstanding_240) ## 7. Inheritance Limits ## total = 10 def find_total(column): total = total + sum(column) return total print(find_total(principal_outstanding_240)) ## 9. Global Variables ## def new_func(): global b b = 20 new_func() print(b)
{ "repo_name": "vipmunot/Data-Analysis-using-Python", "path": "Python Programming Intermediate/Variable Scopes-29.py", "copies": "1", "size": "1345", "license": "mit", "hash": -3463054704487189500, "line_mean": 18.7941176471, "line_max": 86, "alpha_frac": 0.692936803, "autogenerated": false, "ratio": 3.142523364485981, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4335460167485981, "avg_score": null, "num_lines": null }
## 1. The Data Set ## # Weather has been loaded in. print(weather[0]) print(weather[-1]) ## 3. Practice Populating a Dictionary ## superhero_ranks = {} superhero_ranks['Aquaman'] = 1 superhero_ranks['Superman'] = 2 ## 4. Practice Indexing a Dictionary ## president_ranks = {} president_ranks["FDR"] = 1 president_ranks["Lincoln"] = 2 president_ranks["Aquaman"] = 3 fdr_rank = president_ranks["FDR"] lincoln_rank = president_ranks["Lincoln"] aquaman_rank = president_ranks["Aquaman"] ## 5. Defining a Dictionary with Values ## random_values = {"key1": 10, "key2": "indubitably", "key3": "dataquest", 3: 5.6} print(random_values) animals = {7: "raven",8:"goose",9:"duck"} times = {"morning":9,"afternoon":14,"evening":19,"night":23} ## 6. Modifying Dictionary Values ## students = { "Tom": 60, "Jim": 70 } students['Ann'] = 85 students['Tom'] = 80 students['Jim'] += 5 ## 7. The In Statement and Dictionaries ## planet_numbers = {"mercury": 1, "venus": 2, "earth": 3, "mars": 4} jupiter_found = 'jupiter' in planet_numbers earth_found= 'earth' in planet_numbers ## 9. Practicing with the Else Statement ## planet_names = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Neptune", "Uranus"] short_names = [] long_names = [] for item in planet_names: if len(item) > 5: long_names.append(item) else: short_names.append(item) ## 10. Counting with Dictionaries ## pantry = ["apple", "orange", "grape", "apple", "orange", "apple", "tomato", "potato", "grape"] pantry_counts = {} for item in pantry: if item in pantry_counts: pantry_counts[item] += 1 else: pantry_counts[item] = 1 ## 11. Counting the Weather ## weather_counts = {} for item in weather: if item in weather_counts: weather_counts[item] +=1 else: weather_counts[item] = 1
{ "repo_name": "vipmunot/Data-Analysis-using-Python", "path": "Python Programming Beginner/Dictionaries-167.py", "copies": "1", "size": "1834", "license": "mit", "hash": 7421986907022433000, "line_mean": 23.7972972973, "line_max": 94, "alpha_frac": 0.6384950927, "autogenerated": false, "ratio": 2.7291666666666665, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3867661759366666, "avg_score": null, "num_lines": null }
# 1)Thelo na anoikso ena .txt arxeio # 2)Thelo na do ti exei # 3)Thelo na grapso kati # 4)Thelo na ksanakano print to arxeio na do ti egrapsa # 5)Thelo na kleiso to arxeio ## Kano ena random noumero gia na graftei sto arxeio....isa isa gia tin dokimi import random randoms_word = random.randint(1,10) # Dimiourgo tin wr() function...isa isa gia na einai organized def wr(randoms_word): # 1) Edo anoigo to arxeio mou to test.txt pou einai ston idio fakelo f=open('test.txt', 'r+') # 2.a) Edo diavazo to arxeio na do ti exei word = f.read() # 2.b) Edo kano print na do ti exei print word # 3) Edo dokimazo na grapso sto arxeio to random noumero pou ekana new_word = f.write(str(randoms_word)) # 4) Edo ksekinaei to provlima # An anoikso to arxeio me 'r+' den me afinei na grapso # An anoikso to arxeio me 'w' den me afinei na to diavaso # Ti prepei na kano gia na diavaso auto pou egrapsa? # Prepei na kleiso to arxeio kai na to ksananoikso gia diavasma? word2 = f.read() print word2 # 5) Edo kleino to arxeio f.close() wr(randoms_word)
{ "repo_name": "alexsigaras/rover", "path": "examples/write_test.py", "copies": "1", "size": "1109", "license": "mit", "hash": 6553177507049697000, "line_mean": 31.6176470588, "line_max": 78, "alpha_frac": 0.6807935077, "autogenerated": false, "ratio": 2.437362637362637, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3618156145062637, "avg_score": null, "num_lines": null }
## 1. The Time Module ## import time current_time = time.time() print(current_time) ## 2. Converting Timestamps ## import time current_time = time.time() current_struct_time = time.gmtime() current_hour = current_struct_time.tm_hour print(current_hour) ## 3. UTC ## import datetime current_datetime = datetime.datetime.now() current_year = current_datetime.year current_month = current_datetime.month ## 4. Timedelta ## import datetime today = datetime.datetime.now() diff = datetime.timedelta(days = 1) tomorrow = today + diff yesterday = today - diff ## 5. Formatting Dates ## import datetime mystery_date_formatted_string = mystery_date.strftime("%I:%M%p on %A %B %d, %Y") print(mystery_date_formatted_string) ## 6. Parsing Dates ## import datetime mystery_date = datetime.datetime.strptime(mystery_date_formatted_string, "%I:%M%p on %A %B %d, %Y") print(mystery_date) ## 8. Reformatting Our Data ## import datetime for item in posts: item[2] = datetime.datetime.fromtimestamp(float(item[2])) ## 9. Counting Posts from March ## import datetime march_count = 0 for item in posts: if item[2].month == 3: march_count +=1 ## 10. Counting Posts from Any Month ## def no_posts(month_value): march_count = 0 for row in posts: if row[2].month == month_value: march_count += 1 return(march_count) feb_count = no_posts(2) aug_count = no_posts(8)
{ "repo_name": "vipmunot/Data-Analysis-using-Python", "path": "Python Programming Intermediate/Dates in Python-166.py", "copies": "1", "size": "1410", "license": "mit", "hash": -7355587153028510000, "line_mean": 20.0447761194, "line_max": 99, "alpha_frac": 0.685106383, "autogenerated": false, "ratio": 3.0128205128205128, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4197926895820513, "avg_score": null, "num_lines": null }
1. import pandas as pd 2. from sklearn.base import TransformerMixin 3. 4. 5. class FeatureExtractor(TransformerMixin): 6. main_cols = ['country', 'gender', 'ageMin', 'ageMax', 'year'] 7. inci_cols = [ 8. # Other cancers mortality rate 9. 'g_mNasopharynx (C11)', 'g_mBreast (C50)', 'g_mMesothelioma (C45)', 10. 'g_mCorpus uteri (C54)', 'g_mLip, oral cavity, pharynx, larynx and oesophagus (C00-15,C32)', 11. 'g_mMelanoma of skin (C43)', 'g_mMultiple myeloma (C88+C90)', 'g_mUterus (C53-55)', 12. 'g_Brain, central ner', 'g_mKidney (C64)', 13. 14. # incidence of the cancers we are targeting 15. 'incidence X21.0', 'incidence X21.1', 'incidence X21.2', 16. 'incidence X21.3', 'incidence X21.4', 'incidence X21.5', 'incidence X21.6', 17. 'incidence X22.0', 'incidence X22.1', 'incidence X22.2', 'incidence X22.3', 18. 'incidence X22.4', 'incidence X22.5', 'incidence X22.6', 'incidence X22.7', 19. 'incidence X22.8', 20. 'incidence C00-96, C44'] 21. def __init__(self): 22. pass 23. def fit(self, df, y): 24. return self 25. def transform(self, df): 26. df_ = df[self.main_cols + self.inci_cols].copy() 27. df_ = pd.get_dummies(df_, drop_first=False, columns=['country']) 28. df_ = pd.get_dummies(df_, drop_first=True, columns=['gender']) 29. return df_.values
{ "repo_name": "BenSchannes/Epidemium", "path": "Feature_Extractor_NN_2.py", "copies": "1", "size": "1459", "license": "mit", "hash": -5392544926263482000, "line_mean": 46.6333333333, "line_max": 104, "alpha_frac": 0.5812200137, "autogenerated": false, "ratio": 2.315873015873016, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8096419764842493, "avg_score": 0.06013465294610449, "num_lines": 30 }
1、下载安装包 http://dev.mysql.com/downloads/mysql/#downloads 推荐下载通用安装方法的TAR包 http://cdn.mysql.com//Downloads/MySQL-5.7/mysql-5.7.12-linux-glibc2.5-x86_64.tar 2、检查库文件是否存在,如有删除。 [root@localhost Desktop]$ rpm -qa | grep mysql mysql-libs-5.1.52-1.el6_0.1.x86_64 [root@localhost ~]# rpm -e mysql-libs-5.1.52.x86_64 --nodeps [root@localhost ~]# 3、检查mysql组和用户是否存在,如无创建 [root@localhost ~]# cat /etc/group | grep mysqlmysql:x:490: [root@localhost ~]# cat /etc/passwd | grep mysqlmysql:x:496:490::/home/mysql:/bin/bash 默认存在的情况,如无,执行添加命令: [root@localhost ~]#groupadd mysql [root@localhost ~]#useradd -r -g mysql mysql useradd -r参数表示mysql用户是系统用户,不可用于登录系统。 4、解压TAR包,更改所属的组和用户 [root@localhost ~]# cd /usr/local/ [root@localhost local]# tar xvf mysql-5.7.12-linux-glibc2.5-x86_64.tar [root@localhost local]# ls -l total 1306432 -rwxr--r--. 1 root root 668866560 Jun 1 15:07 mysql-5.7.12-linux-glibc2.5-x86_64.tar -rw-r--r--. 1 7161 wheel 638960236 Mar 28 12:54 mysql-5.7.12-linux-glibc2.5-x86_64.tar.gz -rw-r--r--. 1 7161 wheel 29903372 Mar 28 12:48 mysql-test-5.7.12-linux-glibc2.5-x86_64.tar.gz [root@localhost local]# tar xvfz mysql-5.7.12-linux-glibc2.5-x86_64.tar.gz [root@localhost local]# mv mysql-5.7.12-linux-glibc2.5-x86_64 mysql [root@localhost local]# ls -l total 1306436 drwxr-xr-x. 2 root root 4096 Dec 4 2009 bin drwxr-xr-x. 2 root root 4096 Dec 4 2009 etc drwxr-xr-x. 2 root root 4096 Dec 4 2009 games drwxr-xr-x. 2 root root 4096 Dec 4 2009 include drwxr-xr-x. 2 root root 4096 Dec 4 2009 lib drwxr-xr-x. 3 root root 4096 Dec 2 14:36 lib64 drwxr-xr-x. 2 root root 4096 Dec 4 2009 libexec drwxr-xr-x. 9 7161 wheel 4096 Mar 28 12:51 mysql -rw-r--r--. 1 7161 wheel 638960236 Mar 28 12:54 mysql-5.7.12-linux-glibc2.5-x86_64.tar.gz drwxr-xr-x. 2 root root 4096 Dec 4 2009 sbin drwxr-xr-x. 6 root root 4096 Dec 2 14:36 share drwxr-xr-x. 2 root root 4096 Dec 4 2009 src [root@localhost local]# chown -R mysql:root mysql/ [root@localhost local]# cd mysql/ 5、安装和初始化数据库 [root@localhost mysql]# bin/mysql_install_db --user=mysql --basedir=/usr/local/mysql/ --datadir=/usr/local/mysql/data/2016-06-01 15:23:25 [WARNING] mysql_install_db is deprecated. Please consider switching to mysqld --initialize2016-06-01 15:23:30 [WARNING] The bootstrap log isn't empty:2016-06-01 15:23:30 [WARNING] 2016-06-01T22:23:25.491840Z 0 [Warning] --bootstrap is deprecated. Please consider using --initialize instead2016-06-01T22:23:25.492256Z 0 [Warning] Changed limits: max_open_files: 1024 (requested 5000)2016-06-01T22:23:25.492260Z 0 [Warning] Changed limits: table_open_cache: 431 (requested 2000)---------------------- 这一步我安装的时候,第一次不行,所有的重新来了一次,然后出现的是如下提示: [root@localhost mysql]# ./bin/mysqld --initialize --user=mysql --basedir=/usr/local/mysql/ --datadir=/usr/local/mysql/data/ Installing MySQL system tables...OK Filling help tables...OK To start mysqld at boot time you have to copy support-files/mysql.server to the right place for your system PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !To do so, start the server, then issue the following commands: /usr/local/mysql//bin/mysqladmin -u root password 'new-password' /usr/local/mysql//bin/mysqladmin -u root -h 127.0.1.1 password 'new-password' Alternatively you can run: /usr/local/mysql//bin/mysql_secure_installation which will also give you the option of removing the test databases and anonymous user created by default. This is strongly recommended for production servers. See the manual for more instructions. You can start the MySQL daemon with: cd /usr ; /usr/local/mysql//bin/mysqld_safe & You can test the MySQL daemon with mysql-test-run.pl cd mysql-test ; perl mysql-test-run.pl Please report any problems at http://bugs.mysql.com/ The latest information about MySQL is available on the web at http://www.mysql.com Support MySQL by buying support/licenses at http://shop.mysql.com New default config file was created as /usr/local/mysql//my.cnf and will be used by default by the server when you start it. You may edit this file to change server settings WARNING: Default config file /etc/my.cnf exists on the system This file will be read by default by the MySQL serverIf you do not want to use this, either remove it, or use the --defaults-file argument to mysqld_safe when starting the server [root@localhost mysql]# 6、创建mysqld起动和配置文件 [root@localhost mysql]# [root@localhost mysql]# cp -a ./support-files/my-default.cnf /etc/my.cnf [root@localhost mysql]# cp -a ./support-files/mysql.server /etc/init.d/mysqld [root@localhost mysql]# cd bin/ [root@localhost bin]# ./mysqld_safe --user=mysql & [1] 2932 [root@localhost bin]# 2016-06-01T22:27:09.708557Z mysqld_safe Logging to '/usr/local/mysql/data/localhost.localdomain.err'.2016-06-01T22:27:09.854913Z mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data [root@localhost bin]# /etc/init.d/mysqld restart Shutting down MySQL..2016-06-01T22:27:50.498694Z mysqld_safe mysqld from pid file /usr/local/mysql/data/localhost.localdomain.pid ended SUCCESS! Starting MySQL. SUCCESS! [1]+ Done ./mysqld_safe --user=mysql [root@localhost bin]# //设置开机启动 [root@localhost bin]# chkconfig --level 35 mysqld on [root@localhost bin]# 另一种很好的设置MySQL自启动的方式: [root@localhost bin]# echo "service mysqld start" >> /etc/rc.local 或者进入/etc/目录,直接vim rc.local编辑rc.local文件,在最后一行添加“service mysqld start”,保存退出 有时会遇到权限问题: bash: /etc/rc.local: Permission denied 分析: bash 返回 /etc/rc.local: Permission denied 这是因为重定向符号 “>” 也是 bash 的命令。sudo 只是让 echo 命令具有了 root 权限, 但是没有让 “>” 命令也具有root 权限,所以 bash 会认为这个命令没有写入信息的权限。 解决: 使用 bash -c 参数 [root@localhost bin]# sudo bash -c "echo "service mysqld start" >> /etc/rc.local" 6.初始化密码 mysql5.7会生成一个初始化密码,而在之前的版本首次登陆不需要登录。 [root@localhost bin]# cat /root/.mysql_secret # Password set for user 'root@localhost' at 2016-06-01 15:23:25 ,xxxxxR5H9 [root@localhost bin]# ./mysql -uroot -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 2 Server version: 5.7.12 Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> SET PASSWORD = PASSWORD('123456'); Query OK, 0 rows affected, 1 warning (0.00 sec) mysql> flush privileges; Query OK, 0 rows affected (0.00 sec) 上面一步中,如果出现了提示密码过期,可用如下方法解决: [root@localhost bin]# /usr/local/mysql/bin/mysqladmin -u root -p password Enter password:New password: Confirm new password: Warning: Since password will be sent to server in plain text, use ssl connection to ensure password safety. 或者: /usr/local/mysql/bin/mysqladmin -u root -p'<your temp password>' password '<your new password>' 7.添加远程访问权限 mysql> use mysql; Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed mysql> update user set host = '%' where user = 'root'; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select host, user from user; +-----------+-----------+| host | user | +-----------+-----------+ | % | root || localhost | mysql.sys | +-----------+-----------+ 9、更改配置文件和服务的权限 此步一定要改,我当初没改就一直提示说是有一个服务绑定了3306,死都找不出来问题。 先添加环境变量: [root@localhost bin]# vim /etc/profile 最后一行填加: MYSQL_HOME=/usr/local/mysqlexport PATH=$PATH:$MYSQL_HOME/bin 让修改立即生效: [root@localhost bin]# source /etc/profile 再修改两个文件的权限: [root@localhost bin]# [root@localhost bin]# service mysqld stop [root@localhost bin]# chown -R root:root /etc/init.d/mysqld [root@localhost bin]# chown -R root:root /etc/my.cnf 10、修改配置文件 [root@localhost bin]# vim /etc/my.cnf 我的配置文件如下: # For advice on how to change settings please see # http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html # *** DO NOT EDIT THIS FILE. It's a template which will be copied to the # *** DO NOT EDIT THIS FILE. It's a template which will be copied to the # *** default location during install, and will be replaced if you # *** upgrade to a newer version of MySQL. [client]default-character-set=utf8 #避免MySQL的外部锁定,减少出错几率增强稳定性。 socket = /tmp/mysql.sock [mysql]local-infile=1 loose-local-infile=1 [mysqld] # Remove leading # and set to the amount of RAM for the most important data # cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%. # innodb_buffer_pool_size = 128M # Remove leading # to turn on a very important data integrity option: logging # changes to the binary log between backups. # log_bin # These are commonly set, remove the # and set as required. basedir = /usr/local/mysql datadir = /usr/local/mysql/data port = 3306 server_id = 1 character_set_server=utf8 #skip-grant-tables lower_case_table_names=1 #避免MySQL的外部锁定,减少出错几率增强稳定性。 socket = /tmp/mysql.sock skip-external-locking skip-name-resolve log_bin=/usr/local/mysql/log/bin.log log_error=/usr/local/mysql/log/error.log long_query_time=3 slow_query_log=ON slow_query_log_file="/usr/local/mysql/log/slowquery.log" general_log=ON general_log_file=/usr/local/mysql/log/general.log expire_logs_days = 10 # socket = ..... # Remove leading # to set options mainly useful for reporting servers. # The server defaults are faster for transactions and fast SELECTs. # Adjust sizes as needed, experiment to find the optimal values. # join_buffer_size = 128M # sort_buffer_size = 2M # read_rnd_buffer_size = 2M sql_mode=STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_AUTO_VALUE_ON_ZERO,NO_ENGINE_SUBSTITUTION,NO_ZERO_IN_DATE 修改后保存退出 11、重启生效 [root@localhost bin]# /etc/init.d/mysqld restart [root@localhost bin]# netstat -na | grep 3306,如果看到有监听说明服务启动了
{ "repo_name": "yu757371316/MySQL", "path": "yuzicheng/余子成/其他笔记文档/MySQL/配置和学习/Linux下MySQL的安装与配置.py", "copies": "1", "size": "10935", "license": "apache-2.0", "hash": 6691328430260427000, "line_mean": 39.4713114754, "line_max": 636, "alpha_frac": 0.7352911392, "autogenerated": false, "ratio": 2.4886592741935485, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.37239504133935486, "avg_score": null, "num_lines": null }
# 1、恐龙题 # 给两个cvs files里面给了一些数据,格式大概是这样的 # file1 # name,leg_length,diet # file2: # name,stride_length,stance # 两个files里的恐龙的名字是对应的,但是不顺序 # 要求是根据给定的一个公式(输入是leg_length和stride_length)计算出速度,从大到小输出直立行走的恐龙名字 import collections import os def printDinosaur(speedOf, file1, file2): dTable = collections.defaultdict(list) with open(file1, 'r') as csv1, open(file2, 'r') as csv2: for line in csv1: try: dinosaur, leg_length, diet = line.split(',') except TypeError as err: print('Input error: {0}'.format(err)) else: dTable[dinosaur].append(int(leg_length)) for line in csv2: try: dinosaur, stride_length, stance = line.split(',') except TypeError as err: print('Input error: {0}'.format(err)) else: dTable[dinosaur].append(int(stride_length)) col = [(name, dTable[name][0], dTable[name][1]) for name in dTable] col.sort(cmp=lambda a,b: speedOf(a[1], a[2]) - speedOf(b[1], b[2]), reverse=True) print(col) return [elt[0] for elt in col] def speedOf(leg, stride): return leg * stride print(printDinosaur(speedOf, 'Facebook/PE/dinosaur1.csv', 'Facebook/PE/dinosaur2.csv'))
{ "repo_name": "seanxwzhang/LeetCode", "path": "Facebook/PE/dinosaur.py", "copies": "1", "size": "1278", "license": "mit", "hash": 8678646909809414000, "line_mean": 29.1351351351, "line_max": 87, "alpha_frac": 0.6956912029, "autogenerated": false, "ratio": 2.1423076923076922, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3337998895207692, "avg_score": null, "num_lines": null }
#1.单进程: # import requests,time # start_time=time.time() # [requests.get('http://www.liaoxuefeng.com/') for x in range(100)] # print("用时:{}秒".format(time.time()-start_time)) #2.多线程 # import threadpool,requests # def run(url): # r=requests.get(url=url) # pool=threadpool.ThreadPool(10) # reqs=threadpool.makeRequests(run,['http://www.liaoxuefeng.com' for x in range(100)]) # [pool.putRequest(x) for x in reqs] # pool.wait() # print("用时:{}秒".format(time.time()-start_time)) #3.多进程 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # import multiprocessing,time,requests # start_time=time.time() # def run(url): # r=requests.get(url=url) # #print(1) # if __name__=='__main__': # pool=multiprocessing.Pool(10) # [pool.apply_async(run,args=('http://www.liaoxuefeng.com',)) for x in range(100)] # pool.close() # pool.join() # print("用时:{}秒".format(time.time()-start_time)) #4.协程(异步IO) import asyncio, aiohttp, time start_time=time.time() async def run(url): async with aiohttp.ClientSession() as session: async with session.get(url=url) as resp: pass loop=asyncio.get_event_loop() tasks=[asyncio.ensure_future(run('http://www.liaoxuefeng.com')) for x in range(100)] loop.run_until_complete(asyncio.wait(tasks)) print("用时:{}秒".format(time.time()-start_time))
{ "repo_name": "YuHongJun/python-training", "path": "work_one/requestUrlTest.py", "copies": "1", "size": "1373", "license": "mit", "hash": -5040773757337042000, "line_mean": 28.1111111111, "line_max": 86, "alpha_frac": 0.6600458365, "autogenerated": false, "ratio": 2.5972222222222223, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8672164963677774, "avg_score": 0.017020619008889577, "num_lines": 45 }
class Node(object): """链表结构的Node节点""" def __init__(self, data, next_node=None): """Node节点的初始化方法. 参数: data:存储的数据 next:下一个Node节点的引用地址 """ self.__data = data self.__next = next_node @property def data(self): """Node节点存储数据的获取. 返回: 当前Node节点存储的数据 """ return self.__data @data.setter def data(self, data): """Node节点存储数据的设置方法. 参数: data:新的存储数据 """ self.__data = data @property def next_node(self): """获取Node节点的next指针值. 返回: next指针数据 """ return self.__next @next_node.setter def next_node(self, next_node): """Node节点next指针的修改方法. 参数: next:新的下一个Node节点的引用 """ self.__next = next_node class SinglyLinkedList(object): """单向链表""" def __init__(self): """单向列表的初始化方法.""" self.__head = None def find_by_value(self, value): """按照数据值在单向列表中查找. 参数: value:查找的数据 返回: Node """ node = self.__head while (node is not None) and (node.data != value): node = node.next_node return node def find_by_index(self, index): """按照索引值在列表中查找. 参数: index:索引值 返回: Node """ node = self.__head pos = 0 while (node is not None) and (pos != index): node = node.next_node pos += 1 return node def insert_to_head(self, value): """在链表的头部插入一个存储value数值的Node节点. 参数: value:将要存储的数据 """ node = Node(value) node.next_node = self.__head self.__head = node def insert_after(self, node, value): """在链表的某个指定Node节点之后插入一个存储value数据的Node节点. 参数: node:指定的一个Node节点 value:将要存储在新Node节点中的数据 """ if node is None: # 如果指定在一个空节点之后插入数据节点,则什么都不做 return new_node = Node(value) new_node.next_node = node.next node.next = new_node def insert_before(self, node, value): """在链表的某个指定Node节点之前插入一个存储value数据的Node节点. 参数: node:指定的一个Node节点 value:将要存储在新的Node节点中的数据 """ if (node is None) or (self.__head is None): # 如果指定在一个空节点之前或者空链表之前插入数据节点,则什么都不做 return if node == self.__head: # 如果是在链表头之前插入数据节点,则直接插入 self.insert_to_head(value) return new_node = Node(value) pro = self.__head not_found = False # 如果在整个链表中都没有找到指定插入的Node节点,则该标记量设置为True while pro.next_node != node: # 寻找指定Node之前的一个Node if pro.next_node is None: # 如果已经到了链表的最后一个节点,则表明该链表中没有找到指定插入的Node节点 not_found = True break else: pro = pro.next_node if not not_found: pro.next_node = new_node new_node.next_node = node def delete_by_node(self, node): """在链表中删除指定Node的节点. 参数: node:指定的Node节点 """ if self.__head is None: # 如果链表是空的,则什么都不做 return if node == self.__head: # 如果指定删除的Node节点是链表的头节点 self.__head = node.next_node return pro = self.__head not_found = False # 如果在整个链表中都没有找到指定删除的Node节点,则该标记量设置为True while pro.next_node != node: if pro.next_node is None: # 如果已经到链表的最后一个节点,则表明该链表中没有找到指定删除的Node节点 not_found = True break else: pro = pro.next_node if not not_found: pro.next_node = node.next_node def delete_by_value(self, value): """在链表中删除指定存储数据的Node节点. 参数: value:指定的存储数据 """ if self.__head is None: # 如果链表是空的,则什么都不做 return if self.__head.data == value: # 如果链表的头Node节点就是指定删除的Node节点 self.__head = self.__head.next_node pro = self.__head node = self.__head.next_node not_found = False while node.data != value: if node.next_node is None: # 如果已经到链表的最后一个节点,则表明该链表中没有找到执行Value值的Node节点 not_found = True break else: pro = node node = node.next_node if not_found is False: pro.next_node = node.next_node def delete_last_n_node(self, n): """删除链表中倒数第N个节点. 主体思路: 设置快、慢两个指针,快指针先行,慢指针不动;当快指针跨了N步以后,快、慢指针同时往链表尾部移动, 当快指针到达链表尾部的时候,慢指针所指向的就是链表的倒数第N个节点 参数: n:需要删除的倒数第N个序数 """ fast = self.__head slow = self.__head step = 0 while step <= n: fast = fast.next_node step += 1 while fast.next_node is not None: tmp = slow fast = fast.next_node slow = slow.next_node tmp.next_node = slow.next_node def find_mid_node(self): """查找链表中的中间节点. 主体思想: 设置快、慢两种指针,快指针每次跨两步,慢指针每次跨一步,则当快指针到达链表尾部的时候,慢指针指向链表的中间节点 返回: node:链表的中间节点 """ fast = self.__head slow = self.__head while fast.next_node is not None: fast = fast.next_node.next_node slow = slow.next_node return slow def create_node(self, value): """创建一个存储value值的Node节点. 参数: value:将要存储在Node节点中的数据 返回: 一个新的Node节点 """ return Node(value) def print_all(self): """打印当前链表所有节点数据.""" pos = self.__head if pos is None: print("当前链表还没有数据") return while pos.next_node is not None: print(str(pos.data) + " --> ", end="") pos = pos.next_node print(str(pos.data)) def reversed_self(self): """翻转链表自身.""" if self.__head is None or self.__head.next is None: # 如果链表为空,或者链表只有一个节点 return pre = self.__head node = self.__head.next while node is not None: pre, node = self.__reversed_with_two_node(pre, node) self.__head.next = None self.__head = pre def __reversed_with_two_node(self, pre, node): """翻转相邻两个节点. 参数: pre:前一个节点 node:当前节点 返回: (pre,node):下一个相邻节点的元组 """ tmp = node.next_node node.next_node = pre pre = node # 这样写有点啰嗦,但是能让人更能看明白 node = tmp return pre, node def has_ring(self): """检查链表中是否有环. 主体思想: 设置快、慢两种指针,快指针每次跨两步,慢指针每次跨一步,如果快指针没有与慢指针相遇而是顺利到达链表尾部 说明没有环;否则,存在环 返回: True:有环 False:没有环 """ fast = self.__head slow = self.__head while (fast.next_node is not None) and (fast is not None): fast = fast.next_node slow = slow.next_node if fast == slow: return True return False
{ "repo_name": "wangzheng0822/algo", "path": "python/06_linkedlist/singlyLinkedList.py", "copies": "1", "size": "9190", "license": "apache-2.0", "hash": 1583086988806336500, "line_mean": 24.0211267606, "line_max": 87, "alpha_frac": 0.4976076555, "autogenerated": false, "ratio": 2.2261904761904763, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8223171123287647, "avg_score": 0.00012540168056599982, "num_lines": 284 }
# 1.定义一个方法 func,该func可以引入任意多的整型参数,结果返回其中最大与最小的值。 # def func(*num): # result = list(num) # return sorted(result)[0], sorted(result)[len(result) - 1] # 2.定义一个方法func,该func可以引入任意多的字符串参数,结果返回(长度)最长的字符串。 # def func(*string): # result_list = [] # result_list = [(x, len(x)) for x in list(string)] # return sorted(result_list, key=lambda y: y[1], reverse=True)[0][0] # print(func('aaa', 'b', 'vvvvvvvv')) # 3.定义一个方法get_doc(module),module参数为该脚本中导入或定义的模块对象,该函数返回module的帮助文档。 # import time # # # def get_doc(module): # help(module) # print(get_doc(time)) # 例 print get_doc(urllib),则会输出urllib这个模块的帮助文档。 # 4.定义一个方法get_text(f),f参数为任意一个文件的磁盘路径,该函数返回f文件的内容。 # def get_text(f): # file = open(f, 'r') # for x in file.readlines(): # return x # print(get_text('')) # 5.定义一个方法get_dir(folder),folder参数为任意一个文件夹,该函数返回folder文件夹的文件列表。提示(可以了解python的glob模块) # import glob # def get_dir(folder): # return glob.glob(folder) # print(get_dir("/home/blue/python")) # 1 定义一个方法get_num(num),num参数是列表类型,判断列表里面的元素为数字类型。其他类型则报错,并且返回一个偶数列表:(注:列表里面的元素为偶数)。 def get_num(num): if isinstance(num, list): for x in num: if isinstance(x, int) is False: return "the num is not int" return list(filter(lambda y: y % 2 == 0, num)) else: return "the num is not list" assert get_num([2, 1, 30]) == [2, 30] # 2 定义一个方法get_page(url),url参数是需要获取网页内容的网址,返回网页的内容。提示(可以了解python的urllib模块)。 import urllib #def get_page(url): # 3 定义一个方法 func,该func引入任意多的列表参数,返回所有列表中最大的那个元素。 # def func(*num_list): # for x in num_list: # if isinstance(x, list) is False: # return "the num_list is not list" # return sorted(num_list, key=lambda y: len(y), reverse=True)[0] # print(func([1, 2], [1, 2, 3])) # 4 定义一个方法get_dir(f),f参数为任意一个磁盘路径,该函数返回路径下的所有文件夹组成的列表,如果没有文件夹则返回"Not dir"。 # def get_dir(f):
{ "repo_name": "bluedai180/PythonExercise", "path": "Exercise/Method.py", "copies": "1", "size": "2635", "license": "apache-2.0", "hash": -2026009484972654800, "line_mean": 26.0579710145, "line_max": 84, "alpha_frac": 0.6497054097, "autogenerated": false, "ratio": 1.7287037037037036, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.2878409113403704, "avg_score": null, "num_lines": null }
#1. 打印功能提示 print("="*50) print(" 名片管理系统 V0.01") print(" 1. 添加一个新的名片") print(" 2. 删除一个名片") print(" 3. 修改一个名片") print(" 4. 查询一个名片") print(" 5. 显示所有的名片") print(" 6. 退出系统") print("="*50) #用来存储名片 card_infors = [] while True: #2. 获取用户的输入 num = int(input("请输入操作序号:")) #3. 根据用户的数据执行相应的功能 if num==1: new_name = input("请输入新的名字:") new_qq = input("请输入新的QQ:") new_weixin = input("请输入新的微信:") new_addr = input("请输入新的住址:") #定义一个新的字典,用来存储一个新的名片 new_infor = {} new_infor['name'] = new_name new_infor['qq'] = new_qq new_infor['weixin'] = new_weixin new_infor['addr'] = new_addr #将一个字典,添加到列表中 card_infors.append(new_infor) #print(card_infors)# for test elif num==2: pass elif num==3: pass elif num==4: find_name = input("请输入要查找的姓名:") find_flag = 0#默认表示没有找到 for temp in card_infors: if find_name == temp["name"]: print("%s\t%s\t%s\t%s"%(temp['name'], temp['qq'], temp['weixin'], temp['addr'])) find_flag=1#表示找到了 break #判断是否找到了 if find_flag == 0: print("查无此人....") elif num==5: print("姓名\tQQ\t微信\t住址") for temp in card_infors: print("%s\t%s\t%s\t%s"%(temp['name'], temp['qq'], temp['weixin'], temp['addr'])) elif num==6: break else: print("输入有误,请重新输入") print("")
{ "repo_name": "nacker/pythonProject", "path": "01Base/03/04-名片关系系统.py", "copies": "2", "size": "1857", "license": "apache-2.0", "hash": -142679517496484860, "line_mean": 20.8382352941, "line_max": 96, "alpha_frac": 0.4962962963, "autogenerated": false, "ratio": 2.1742313323572473, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.36705276286572475, "avg_score": null, "num_lines": null }
# 1. 给你一本书(input),统计里面词频最高的10个单词 # 先是说考虑input是一个大string的情况,用hashmap+maxheap直接秒就行了,注意一些细节处理就好,我写完被挑出一些小毛病,改完小哥很满意然后上follow up: input是一个文件?改下代码的input处理就好了,按行读入按单词存入hashmap。写完继续follow up:如果input文件很大,hashmap爆了内存怎么办?只考虑ASCII。然后开始估算大概要用多少内存,算下来几M到几十M不等的内存占用,然后pass import collections import heapq def word_frequency(input, n): """ input: list[str] n: int """ table, heap, res = collections.defaultdict(0), [], [] for word in input: input[word] += 1 heap = [(-table[word], word) for word in table] heapq.heapify(heap) for _ in xrange(n): res.append(heapq.heappop()) return res def file_word_frequence(file, n): table, heap, res = collections.defaultdict(0), [], [] with open(file, 'r') as input: for word in input: input[word] += 1 heap = [(-table[word], word) for word in table] heapq.heapify(heap) for _ in xrange(n): res.append(heapq.heappop()) return res
{ "repo_name": "seanxwzhang/LeetCode", "path": "Facebook/PE/word_frequency.py", "copies": "1", "size": "1279", "license": "mit", "hash": 2421095081970710000, "line_mean": 32.4482758621, "line_max": 225, "alpha_frac": 0.657378741, "autogenerated": false, "ratio": 1.9695121951219512, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3126890936121951, "avg_score": null, "num_lines": null }
#1에서 10000까지의 자연수의 각 자릿수에 3,9가 있으면 짝을, 6이 있으면 뽁짝을, 2,4,8은 뽁을 출력한다. #단, 순서를 지킨다. count=0 #문자를 쓸지 숫자를 쓸지 판단하기 위함 dictionary = {} #각 숫자의 모든 자리를 검사해서 자리번호가 key, 표시할 대상이 value인 순서쌍을 저장한다. while True: max = int(input("숫자를 입력하세요 : ")) if max <1 or max >10000: #말은 이렇게 했지만 이것만 지우면 모든 자연수를 다 할 수 있다. 나도 내가 두렵다. 나란 녀석... print("1이상 10000이하의 숫자만 입력할 수 있습니다.") else: # max가 유효한 범위의 숫자라면, for number in range(1,max+1): number_of_number = len(str(number)) #자릿수를 number_of_number에 저장 if number%20 == 0 or number == max: #줄바꿈을 해야하는 숫자들이라면, number = str(number) for i in range(0, number_of_number): #0번 자리부터 최대 4번 자리까지 각각의 숫자를 검사한다 if number[i] in ["3", "9"]: #i번자리 숫자가 3,9면 순서쌍 {i : "짝"} 을 dictionary에 저장 dictionary[i] = "짝" count = count + 1 elif number[i] == "6": #i번자리 숫자가 6이면 순서쌍 {i : "뽁짝"} 을 dictionary에 저장 dictionary[i] = "뽁짝" count = count + 1 elif number[i] in ["2", "4", "8"]: #i번자리 숫자가 2,4,8이면 순서쌍 {i : "뽁"} 을 dictionary에 저장 dictionary[i] = "뽁" count = count + 1 else: #i번자리 숫자가 1,5,7이면 순서쌍 {i : ""} 을 dictionary에 저장(특징없는 숫자는 count세지 않는다) dictionary[i] = "" if count == 0: #그냥 숫자 출력 print(number) #줄바꿈 한다 else: for i in range(0, number_of_number): #dictionary에 저장했던 key들을 순서대로 불러온다 print(dictionary[i], end="") print("") #줄바꿈 한다 dictionary={} #다음 number의 검사를 위해 dictionary와 count를 비워둔다 count=0 else: #줄바꿈을 하지 않아야 하는 숫자들이라면, number = str(number) for i in range(0, number_of_number): if number[i] in ["3", "9"]: dictionary[i] = "짝" count = count + 1 elif number[i] == "6": dictionary[i] = "뽁짝" count = count + 1 elif number[i] in ["2", "4", "8"]: dictionary[i] = "뽁" count = count + 1 else: dictionary[i] = "" if count == 0: print(number, end=" ") #줄바꿈 안하고 띄어쓰기 한번 한다 else: for i in range(0, number_of_number): print(dictionary[i], end="") print("", end=" ") #줄바꿈 안한고 띄어쓰기 한번 한다 dictionary = {} count = 0
{ "repo_name": "imn00133/pythonSeminar17", "path": "exercise/369/Sehun/10_14_369_final_ppokjjak.py", "copies": "1", "size": "3485", "license": "mit", "hash": -2349220524865442300, "line_mean": 47.7857142857, "line_max": 104, "alpha_frac": 0.4254851703, "autogenerated": false, "ratio": 1.8378196500672948, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.2763304820367295, "avg_score": null, "num_lines": null }
1#!/usr/bin/env python2.7 """MongoDB hub for insertion of data into our servers. This module inserts into GVA2015_data collection documents with the following structure:: { "_id": ObjectID(...), "house": HOUSE_NAME, "basetime": DATE VALUE IN TIMESTAMP, "topic": MQTT TOPIC WITH '/' REPLACED BY '.', "delta_times": AN ARRAY, "values": ANOTHER ARRAY } """ import bson import datetime import json import Queue import time import threading import traceback import raspi_mon_sys.LoggerClient as LoggerClient import raspi_mon_sys.Scheduler as Scheduler import raspi_mon_sys.Utils as Utils PENDING_DOCUMENTS_LENGTH_WARNING = 10000 # expected 40MB of messages for warning PENDING_DOCUMENTS_LENGTH_ERROR = 30000 # expected 120MB of messages for data loss PERIOD = 3600 # every 3600 seconds (1 hour) we send data to hour server assert PENDING_DOCUMENTS_LENGTH_ERROR > PENDING_DOCUMENTS_LENGTH_WARNING raspi_mac = Utils.getmac() logger = None mqtt_client = None house_data = None lock = threading.RLock() pending_documents = [] raspimon_message_queues = {} forecast_message_queues = {} def __enqueue_raspimon_message(client, userdata, topic, message): timestamp = message["timestamp"] data = message["data"] basetime = int(timestamp // PERIOD * PERIOD) lock.acquire() q = raspimon_message_queues.setdefault( (topic,basetime), Queue.Queue() ) lock.release() delta_time = timestamp - basetime q.put( (delta_time, data) ) logger.debug("%s %f %f %f %s", topic, float(basetime), float(timestamp), float(delta_time), str(data)) def __enqueue_forecast_message(client, userdata, topic, message): timestamp = message["timestamp"] basetime = int(timestamp // PERIOD * PERIOD) lock.acquire() q = forecast_message_queues.setdefault( (topic,basetime), Queue.Queue() ) lock.release() q.put( message ) logger.debug("%s %f %s", topic, float(timestamp), str(message)) def __on_mqtt_connect(client, userdata, rc): client.subscribe("raspimon/#") client.subscribe("forecast/#") def __on_mqtt_message(client, userdata, msg): global raspimon_message_queues topic = msg.topic.replace("/",".") message = json.loads(msg.payload) if topic.startswith("raspimon"): __enqueue_raspimon_message(client, userdata, topic, message) elif topic.startswith("forecast"): __enqueue_forecast_message(client, userdata, topic, message) else: raise ValueError("Unknown MQTT topic " + topic) def __configure_mqtt(client): client.on_connect = __on_mqtt_connect client.on_message = __on_mqtt_message def __build_raspimon_documents(key): global raspimon_message_queues topic,basetime = key q = raspimon_message_queues.pop(key) q.put('STOP') data_pairs = [ x for x in iter(q.get, 'STOP') ] data_pairs.sort(key=lambda x: x[0]) delta_times,values = zip(*data_pairs) document = { "house" : house_data["name"], "basetime" : datetime.datetime.utcfromtimestamp(basetime), "topic" : topic, "delta_times" : delta_times, "values" : values } logger.info("New document for topic= %s basetime= %d with n= %d", topic, int(basetime), len(delta_times)) return [ document ] def __build_forecast_documents(key): global forecast_message_queues topic,basetime = key q = forecast_message_queues.pop(key) q.put('STOP') messages = [ x for x in iter(q.get, 'STOP') ] messages.sort(key=lambda x: x["timestamp"]) time2dt = datetime.datetime.utcfromtimestamp for doc in messages: doc["timestamp"] = time2dt(doc["timestamp"]) doc["periods_start"] = [ time2dt(x) for x in doc["periods_start"] ] doc["periods_end"] = [ time2dt(x) for x in doc["periods_end"] ] doc["house"] = house_data["name"] doc["topic"] = topic logger.info("New documents for topic= %s basetime= %d with n= %d", topic, int(basetime), len(messages)) return messages def __upload_all_data(db, build_documents, queues): insert_batch = [ y for x in queues.keys() for y in build_documents(x)] db.GVA2015_data.insert(insert_batch) logger.info("Inserted %d documents", len(insert_batch)) def __build_after_deadline_documents(build_docs, queues, t): lock.acquire() keys = queues.keys() lock.release() batch = [ y for x in keys if t - x[1] > PERIOD for y in build_docs(x) ] return batch def start(): """Opens connections with logger, MongoDB and MQTT broker.""" global logger global mqtt_client global house_data logger = LoggerClient.open("MongoDBHub") mqtt_client = Utils.getpahoclient(logger, __configure_mqtt) mongo_client = Utils.getmongoclient(logger) db = mongo_client["raspimon"] col = db["GVA2015_houses"] house_data = col.find_one({ "raspi":raspi_mac }) assert house_data is not None mongo_client.close() def stop(): mongo_client = Utils.getmongoclient(logger) db = mongo_client["raspimon"] # close MQTT broker connection mqtt_client.disconnect() # force sending data to MongoDB __upload_all_data(db, __build_raspimon_documents, raspimon_message_queues) __upload_all_data(db, __build_forecast_documents, forecast_message_queues) if len(pending_documents) > 0: db.GVA2015_data.insert(pending_documents) # close rest of pending connections mongo_client.close() logger.close() def upload_data(): try: mongo_client = Utils.getmongoclient(logger) db = mongo_client["raspimon"] t = time.time() raspimon_batch = __build_after_deadline_documents(__build_raspimon_documents, raspimon_message_queues, t) forecast_batch = __build_after_deadline_documents(__build_forecast_documents, forecast_message_queues, t) global pending_documents insert_batch = raspimon_batch + forecast_batch + pending_documents pending_documents = [] try: if len(insert_batch) > 0: db.GVA2015_data.insert(insert_batch) except: pending_documents = insert_batch if len(pending_documents) > PENDING_DOCUMENTS_LENGTH_ERROR: logger.error("Pending %s messages is above data loss threshold %d, sadly pending list set to zero :S", len(pending_documents), PENDING_DOCUMENTS_LENGTH_ERROR) pending_documents = [] # data loss here :'( elif len(pending_documents) > PENDING_DOCUMENTS_LENGTH_WARNING: logger.alert("Pending %s messages is above warning threshold %d, data loss will occur at %d", len(pending_documents), PENDING_DOCUMENTS_LENGTH_WARNING, PENDING_DOCUMENTS_LENGTH_ERROR) else: logger.warning("Connection with database is failing") raise logger.info("Inserted %d documents", len(insert_batch)) mongo_client.close() except: print "Unexpected error:", traceback.format_exc() logger.error("Unexpected error: %s", traceback.format_exc()) if __name__ == "__main__": Scheduler.start() start() Scheduler.repeat_o_clock_with_offset(PERIOD*1000, PERIOD/12*1000, upload_data) try: while True: time.sleep(60) except: stop() raise
{ "repo_name": "ESAI-CEU-UCH/raspi-monitoring-system", "path": "raspi_mon_sys/MongoDBHub.py", "copies": "1", "size": "7589", "license": "mit", "hash": 35571248033360536, "line_mean": 35.6618357488, "line_max": 118, "alpha_frac": 0.6334167875, "autogenerated": false, "ratio": 3.6485576923076923, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9719186636041923, "avg_score": 0.012557568753153956, "num_lines": 207 }
1 # !/usr/bin/env python3 # -*- coding: utf-8 -*- import cv2 import os import numpy as np import dlib import sklearn.decomposition import pickle import mappings import copy # Emotion tags in ascending order emotions = ['neutral', 'anger', 'contempt', 'disgust', 'fear', 'happiness', 'sadness', 'surprise'] root_path = "/home/keyran/Documents/Teaching/2016/Дипломники/Datasets/Ck_plus/" images_path = root_path + "cohn-kanade-images" emotion_labels_path = root_path + "Emotion" cascadePath = "data/Cascades/haarcascade_frontalface_alt.xml" faceCascade = cv2.CascadeClassifier(cascadePath) frontal_face_detector = dlib.get_frontal_face_detector() pose_model = dlib.shape_predictor("data/ShapePredictor/shape_predictor_68_face_landmarks.dat") clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) class Face: def __init__(self, filepath=None, image=None, rectangle=None, label=None): if (filepath is None and image is None): raise ValueError("You must scpecify either filepath or image") self._filepath = filepath self._image = image self._tilt = None self._milestones = None self._center = None self.emotions = None self.label = label self.rectangle = rectangle def image(self): if not self._image is None: return self._image else: return cv2.imread(self._filepath) def milestones(self): if self.rectangle is None: raise Exception("The face rectangle hasn't been set") if self._milestones is None: gray_image = cv2.cvtColor(self.image(), cv2.COLOR_RGB2GRAY) clahe_frame = clahe.apply(gray_image) milestones = pose_model(clahe_frame, self.rectangle) arr = np.ndarray((milestones.num_parts, 2)) for i in range(milestones.num_parts): arr[i, 0] = milestones.part(i).x arr[i, 1] = milestones.part(i).y self._milestones = arr return self._milestones @staticmethod def fabric(filepath=None, image=None, label=None): if (filepath is None and image is None): raise ValueError("You must scpecify either filepath or image") faces = [] if filepath: image = cv2.imread(filepath) faces = frontal_face_detector(image) if len(faces) != 0: return [Face(filepath=filepath, image=image if not filepath else None, rectangle=face, label=label) for face in faces] else: faces = faceCascade.detectMultiScale(image) if len(faces) != 0: ret = [] for face in faces: x = face[0] y = face[1] x1 = x + face[2] y1 = y + face[3] ret.append(dlib.rectangle( int(x), int(y), int(x1), int(y1))) return [Face(filepath=filepath, image=image if not filepath else None, rectangle=face, label=label) for face in ret] else: return [] def tilt(self): if self._tilt is None: tilt = 180 - np.arctan2(self.milestones()[45][1] - self.milestones()[39][1], self.milestones()[39][0] - self.milestones()[45][0]) * 180 / np.pi self._tilt = tilt if tilt < 180 else tilt - 360 return self._tilt def center(self): if self._center is None: self._center = (self.milestones()[39][0] + self.milestones()[45][0] / 2, self.milestones()[39][1] + self.milestones()[45][1] / 2) return self._center class FaceSet: def __init__(self, faces, maps = []): self.faces = faces self.permutation = None self.mappings = maps self.emotions = None def generate_training_data(self): data = np.array([f.milestones() for f in self.faces]) labels = np.array([f.label for f in self.faces]) for mapping in self.mappings: if type(mapping) == mappings.PCAMapping: continue data, labels = mapping.training_mapping(data, labels) return data.reshape(len(labels),-1), labels def generate_data(self): data = np.array([f.milestones() for f in self.faces]) data_len = len(data) for mapping in self.mappings: data = mapping.classification_mapping(data) return data.reshape(data_len,-1) def generate_sets(self, train_size=0.6, validation_size=0.2, test_size=0.2, permutation=None): points,labels = self.generate_training_data() if permutation: self.permutation = permutation if self.permutation is None: self.permutation = np.random.permutation(points.shape[0]) training_count = int(points.shape[0] * train_size) validation_count = int(points.shape[0] * validation_size) training_data, validation_data, test_data = np.split(points[self.permutation], [training_count, validation_count + training_count]) training_labels, validation_labels, test_labels = np.split(labels[self.permutation], [training_count, validation_count + training_count]) for mapping in self.mappings: if type(mapping) == mappings.PCAMapping: mapping.pca_init (training_data) training_data = mapping.classification_mapping(training_data) validation_data = mapping.classification_mapping(validation_data) test_data = mapping.classification_mapping(test_data) return {"train_data": training_data, "train_labels": training_labels, "valid_data": validation_data, "valid_labels": validation_labels, "test_data": test_data, "test_labels": test_labels} def save(self, filename): with open(filename, 'wb') as f: pickle.dump(self, f) @staticmethod def load(filename): with open(filename, 'rb') as f: return pickle.load(f) def get_emotion(subject, series): path = emotion_labels_path + "/" + subject + "/" + series if not os.path.exists(path): return -1 files = os.listdir(path) if len(files) == 0: return -1 with open(path + "/" + files[0], 'r') as fin: str_ = fin.readline() return int(float(str_)) def load_all(): faces = [] for p1 in os.scandir(images_path): subject = p1.name if not p1.is_dir(): continue for p2 in os.scandir(p1.path): if not p2.is_dir(): continue num = p2.name for p3 in os.scandir(p2.path): files_count = len(list(os.scandir(p2.path))) if not p3.is_file(): continue image = p3.path # print (image) # Начальные изображения - нейтральные if int(image.rsplit("_")[-1][:-4]) > files_count / 4: emotion = get_emotion(subject, num) if emotion == -1: continue else: emotion = 0 faces.append(Face.fabric(filepath=p3.path, label=emotion)[0]) print(len(faces)) return FaceSet(faces) if __name__ == '__main__': try: face_set = FaceSet.load("data/TrainingData/training_data.dat") except: face_set = load_all() pca_face_set = copy.deepcopy(face_set) face_set.mappings = (mappings.DropContemptMapping(), mappings.ZoomAndTranslateMapping(), mappings.ImageMirrorMapping(), mappings.NormalizeMapping(), ) pca = mappings.PCAMapping(keep_variance=0.99) pca_face_set.mappings = (mappings.DropContemptMapping(), mappings.ZoomAndTranslateMapping(), mappings.ImageMirrorMapping(), mappings.NormalizeMapping(), pca) face_set.save("data/TrainingData/training_data.dat") if(input("Generate training data? (yes/no) ")=="yes"): dat = face_set.generate_sets() face_set.save("data/TrainingData/training_data.dat") pickle.dump(dat, open("data/TrainingData/pickled_generated_sets",'wb')) pca_dat = pca_face_set.generate_sets() pickle.dump(pca_dat, open("data/TrainingData/pickled_generated_sets_pca",'wb')) pickle.dump(pca, open("data/TrainingData/pcamapping.dat", 'wb'))
{ "repo_name": "mkeyran/EmotionRecognizer", "path": "preprocess.py", "copies": "1", "size": "8941", "license": "mit", "hash": 6960509125343195000, "line_mean": 37.3620689655, "line_max": 119, "alpha_frac": 0.5579775281, "autogenerated": false, "ratio": 3.877995642701525, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9905896656814426, "avg_score": 0.006015302797419937, "num_lines": 232 }
# 1/usr/bin/env python3 # Sending data over a stream but delimited as length-prefixed blocks import socket import struct header_struct = struct.Struct('!I') # message upto 2 ^ 32 -1 in length def recvall(sock, length): blocks = [] while length: block = sock.recv(length) if not block: raise EOFError('Socket closed with {} bytes left'.format(length)) length -= len(block) blocks.append(block) return b''.join(blocks) def get_blocks(sock): data = recvall(sock, header_struct.size) (block_length, ) = header_struct.unpack(data) return recvall(sock, block_length) def put_blocks(sock, message): block_length = len(message) sock.send(header_struct.pack(block_length)) sock.send(message) def server(address): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(address) sock.listen(1) print('Run this script in another window with -c option to connect') print('Listening at', sock.getsockname()) sc, sockname = sock.accept() print('Accepted connection from', sockname) sock.shutdown(socket.SHUT_WR) while True: block = get_blocks(sc) if not block: break print('Block says:', repr(block)) sc.close() sock.close() def client(address): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(address) sock.shutdown(socket.SHUT_RD) put_blocks(sock, b'Beautiful is better than ugly.') put_blocks(sock, b'Explicit is better than implicit') put_blocks(sock, b'Simple is better than complex') put_blocks(sock, b'') sock.close() if __name__ == '__main__': import argparse parser = argparse.ArgumentParser( description='Transmit and Receive blocks over TCP') parser.add_argument('hostname', nargs='?', default='127.0.0.1', help='IP address or hostname (default: %(default)s)') parser.add_argument('-c', action='store_true', help='run as client') parser.add_argument('-p', type=int, metavar='port', default=1060, help='TCP port number (default: %(default)s') args = parser.parse_args() function = client if args.c else server function((args.hostname, args.p))
{ "repo_name": "gauravssnl/python3-network-programming", "path": "blocks.py", "copies": "1", "size": "2331", "license": "mit", "hash": 3773237586894841300, "line_mean": 30.5, "line_max": 77, "alpha_frac": 0.6469326469, "autogenerated": false, "ratio": 3.6708661417322834, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9817798788632284, "avg_score": 0, "num_lines": 74 }
# 1/usr/bin/env python3 # UDP client and server for broadcast messages on a local LAN import socket BUFFSIZE = 65535 def server(interface, port): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((interface, port)) print("listening for datagrams at {}".format(sock.getsockname())) while True: data, address = sock.recvfrom(BUFFSIZE) text = data.decode('ascii') print('The client at {} says {!r}'.format(address, text)) def client(network, port): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) text = 'Broadcast Datagram!' sock.sendto(text.encode('ascii'), (network, port)) if __name__ == '__main__': import argparse choices = {'server': server, 'client': client} parser = argparse.ArgumentParser(description='Send/Receive UDP broadcast') parser.add_argument('role', choices=choices, help='which role to take') parser.add_argument( 'host', help='interface the server listens at, network the client connects to') parser.add_argument('-p', metavar='PORT', type=int, default=1060, help='UDP port(default 1060)') args = parser.parse_args() function = choices[args.role] function(args.host, args.p)
{ "repo_name": "gauravssnl/python3-network-programming", "path": "udp_broadcast.py", "copies": "1", "size": "1309", "license": "mit", "hash": -8288777238236095000, "line_mean": 34.3783783784, "line_max": 87, "alpha_frac": 0.6653934301, "autogenerated": false, "ratio": 3.7082152974504248, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9872073101014798, "avg_score": 0.0003071253071253071, "num_lines": 37 }
#1/usr/bin/env python from mechanize import Browser from BeautifulSoup import BeautifulSoup outfile = open("artscraper.txt", "w") mech = Browser() url = "http://www.jerseyarts.com/OnlineGuide.aspx?searchType=advanced&searchTerm=D%3ad7%3bR%3ar1%2cr2%2cr3%2cr4%3bSp%3a0%3bGc%3a0%3bF%3a0" page = mech.open(url) html = page.read() soup = BeautifulSoup(html) for row in soup.findAll('table', {"class" : "GuideResultInfoWrapper"}): name = row.find('div', {"class" : "GuideResultListingName"}).a.string street = row.find('div', {"class" : "GuideResultAddress"}).span.string city = street.findNext('span').string record = (name, street, city) print >> outfile, "; ".join(record) outfile.close() # a sample of the html structure of the website # <div id="ctl00_wpmSiteWide_gwpGuideSearchResults1_GuideSearchResults1_rptSearchResults_ctl01_pnlOrgInfo" class="GuideResultAlternateRow"> # <table cellpadding="0" cellspacing="0" border="0" class="GuideResultInfoWrapper"> # <tr> # <td style="text-align:center;width:113px;"> # <a id="ctl00_wpmSiteWide_gwpGuideSearchResults1_GuideSearchResults1_rptSearchResults_ctl01_lnkGuideDetailFromImage" title='View details for "Artists&squot; Gallery"' href="GuideDetail.aspx?listingID=665dd1b1-7386-4479-aa10-d9073108afa5"> ## <img id="ctl00_wpmSiteWide_gwpGuideSearchResults1_GuideSearchResults1_rptSearchResults_ctl01_imgOrgImage" src="FileHandlers/orgImageThumb.ashx?listingID=665dd1b1-7386-4479-aa10-d9073108afa5" style="border-width:0px;" /> # </a> # </td> # <td> # <div class="GuideResultListingName"> ## Artists' Gallery # </a> # </div> # <div class="GuideResultAddress"> # <span id="ctl00_wpmSiteWide_gwpGuideSearchResults1_GuideSearchResults1_rptSearchResults_ctl01_lblAddress"> ## 18 Bridge Street # </span> # <br /> # <span id="ctl00_wpmSiteWide_gwpGuideSearchResults1_GuideSearchResults1_rptSearchResults_ctl01_lblCitySateZip"> # Lambertville, NJ 08530 # </span> # </div> ## <div> # <span id="ctl00_wpmSiteWide_gwpGuideSearchResults1_GuideSearchResults1_rptSearchResults_ctl01_lblDescription"> # <span id="ctl00_wpmSiteWide_gwpGuideSearchResults1_GuideSearchResults1_rptSearchResults_ctl01_lblDescription" class="GuideResultDescription"> # Artists' Gallery is a partnership of eighteen professional visual artists who cooperatively administer, staff and exhibit ## <a href="GuideDetail.aspx?listingID=665dd1b1-7386-4479-aa10-d9073108afa5" title="View Event Details"> # ...more # </a> # </span> # </span> # </div> # </td> # <td align="right" valign="top"> # </td> # </tr> # </table> # </div>
{ "repo_name": "tommeagher/Scrapers", "path": "artscraper/artscrape.py", "copies": "1", "size": "3591", "license": "mit", "hash": -4064488765503823000, "line_mean": 56.9193548387, "line_max": 266, "alpha_frac": 0.5360623782, "autogenerated": false, "ratio": 3.5838323353293413, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4619894713529341, "avg_score": null, "num_lines": null }
#1/usr/bin/env python #mechanize acts as an browser to collect html response from mechanize import Browser #beautifulsoup lets you strip out the html and parse it through its tree from BeautifulSoup import BeautifulSoup #csvkit allows you to output to a csv file easily from csvkit.unicsv import UnicodeCSVWriter #re handles regular expressions import re #open a csvfile to write to it, set a delimiter and write the header row outfile = open("sitesdirt.csv", "w") w = UnicodeCSVWriter(outfile,delimiter=",",encoding="Cp1252") w.writerow(['name','url']) mech = Browser() url = "http://www.state.nj.us/nj/govinfo/county/localgov.html" page = mech.open(url) html = page.read() soup = BeautifulSoup(html) #look for the section with the id anchorSection, this is the main body of the url listings for row in soup.findAll('div', {"id" : "anchorSection"}): #ignore the rows with anchor tags without an href tag for anchor in row.findAll('a', href=True): name = anchor.string #give me whatever is in the href call, the actual url of the link url = anchor['href'].decode() record = (name, url) w.writerow(record) outfile.close() #now add a re parser to clean it up for import, stripping out the empty anchors without town names infile = open("sitesdirt.csv", "r") outfile = open("townsites.csv", "w") for line in infile: #keep the header row if re.match("name,url", line): print >> outfile,line, if re.findall(".http:", line): print >> outfile,line, infile.close() outfile.close()
{ "repo_name": "tommeagher/Scrapers", "path": "townsites/townscrape.py", "copies": "1", "size": "1545", "license": "mit", "hash": -951006210631249200, "line_mean": 31.8936170213, "line_max": 98, "alpha_frac": 0.7113268608, "autogenerated": false, "ratio": 3.5354691075514872, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4746795968351487, "avg_score": null, "num_lines": null }
#1/usr/bin/env python import sys import re CHROM=0 POS=1 INFO=7 GT=9 def main(): if len(sys.argv) == 1: vcf_file = sys.stdin else: vcf_file = open(sys.argv[1]) file_out = sys.stdout file_out.write("Chrom\tPos\tAF\tMQ\tGT\tEffect\tImpact\tGene_name\n") for line in vcf_file: if line.lstrip()[0] != "#": file_out.write(extract_fields(line)) def extract_fields(line): fields = line.rstrip("\n").split("\t") new_line = "\t".join( (fields[CHROM],fields[POS])) new_line += "\t"+ extract_AF(fields[INFO]) new_line += "\t"+ extract_MQ(fields[INFO]) new_line += "\t"+ extract_GT(fields[GT]) new_line += "\t"+ "\t".join(extract_effect(fields[INFO])) return new_line+"\n" def extract_GT(field_gt): comma_pos = field_gt.find(":") return field_gt[:comma_pos] def extract_AF(field_info): af_pos = field_info.find("AF=") af_semicolon = field_info.find(";",af_pos) return field_info[af_pos+3:af_semicolon] def extract_MQ(field_info): mq_pos = field_info.find("MQ=") mq_semicolon = field_info.find(";",mq_pos) return field_info[mq_pos+3:mq_semicolon] def extract_effect(field_info): eff_pos = field_info.find("EFF=") result = ["-"] *3 if eff_pos > -1: eff_semicolon = field_info.find(";",eff_pos) effect_line = field_info[eff_pos+4:eff_semicolon] eff_name_delim = effect_line.find("(") eff_name = effect_line[:eff_name_delim] eff_fields = effect_line[eff_name_delim+1:-1].split("|") result = (eff_name,eff_fields[0],eff_fields[5]) return result if __name__ == "__main__": main()
{ "repo_name": "maubarsom/biotico-tools", "path": "TcIV-scripts/VCFPhaseEff2table.py", "copies": "1", "size": "1529", "license": "apache-2.0", "hash": 4579206966587522600, "line_mean": 22.1666666667, "line_max": 70, "alpha_frac": 0.6461739699, "autogenerated": false, "ratio": 2.4661290322580647, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3612303002158065, "avg_score": null, "num_lines": null }
1#!/usr/bin/env python try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup version = '0.9.6' setup(name='mi-instrument', version=version, description='OOINet Marine Integrations', url='https://github.com/oceanobservatories/mi-instrument', license='BSD', author='Ocean Observatories Initiative', author_email='contactooici@oceanobservatories.org', keywords=['ooici'], packages=find_packages(), package_data={ '': ['*.yml'], 'mi.platform.rsn': ['node_config_files/*.yml'], }, dependency_links=[ ], test_suite='pyon', entry_points={ 'console_scripts': [ 'run_driver=mi.core.instrument.wrapper:main', 'playback=mi.core.instrument.playback:main', 'analyze=mi.core.instrument.playback_analysis:main', 'oms_extractor=mi.platform.rsn.oms_extractor:main', 'shovel=mi.core.shovel:main', 'oms_aa_server=mi.platform.rsn.oms_alert_alarm_server:main', 'zplsc_echogram=mi.dataset.driver.zplsc_c.zplsc_echogram_generator:main', ], }, )
{ "repo_name": "oceanobservatories/mi-instrument", "path": "setup.py", "copies": "1", "size": "1215", "license": "bsd-2-clause", "hash": 983015008068370800, "line_mean": 31.8378378378, "line_max": 87, "alpha_frac": 0.6024691358, "autogenerated": false, "ratio": 3.5319767441860463, "config_test": false, "has_no_keywords": true, "few_assignments": false, "quality_score": 0.4634445879986046, "avg_score": null, "num_lines": null }
#1/usr/bin/env python # rss locker filetypes_you_want = ".jpg .png .tiff .gif .jpeg .webp".split(" ") def get_file_text(file_path): # returns all text from a file. # Warning this may block up scripts for long files. with open(file_path,"r") as f: return(str(f.read())) def script_path(include_name=False): from os import path full_path = path.realpath(__file__) if include_name: return(full_path) else: full_path = "/".join( full_path.split("/")[0:-1] ) + "/" return(full_path) def grep(link): from urllib2 import urlopen return urlopen(link).read() def check_if_link(s,req_http=True): # Checks at the input is a legitimate link. allowed_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%" if req_http and "http" not in s: return(False) if "://" in s: for i in s: if i not in allowed_chars: return(False) return(True) return(False) def extract_links(url): # extracts all links from a URL and returns them as a list # by: Cody Kochmann def grep(link): try: from urllib2 import urlopen response = urlopen(link) return(response.read()) except: pass def check_if_link(s,req_http=True): # Checks at the input is a legitimate link. allowed_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'*+,;=%" if req_http and "http" not in s: return(False) if "://" in s: for i in s: if i not in allowed_chars: return(False) return(True) return(False) c_links = [] link_being_built = "" allowed_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&*+,;=%" collected_html=grep(url) if collected_html is not None: for i in collected_html: if i in allowed_chars: link_being_built+=i else: if link_being_built not in c_links: if check_if_link(link_being_built): if ".html" not in link_being_built: c_links.append(link_being_built) link_being_built="" return(c_links) def collect_links(links): collected_links=[] output = [] for i in links: for link in list(extract_links(i)): correct = False for t in filetypes_you_want: if t in link: correct = True if correct: output.append(link) print(link) return(output) def list_dir(d): from os import listdir return(listdir(d)) def random_string(): import random import string return "".join([random.SystemRandom().choice(string.digits + string.letters) for i in range(16)]) def download_file(url): from urllib2 import urlopen file_n = url.split('/')[-1] output_path = script_path()+"pictures/" if "?" in file_n or len(file_n) > 30: for i in filetypes_you_want: if i in file_n: file_n=random_string()+i if file_n in list_dir(output_path): print(file_n+" already downloaded") return(False) print("downloading: "+file_n) response = urlopen(url) data = response.read() with open(output_path+file_n, "w") as f: f.write(data) print("finished: "+file_n) def multithreaded_process(arg_list, run_process, max_threads=4): # runs arg_list through run_process multithreaded from multiprocessing import Pool pool = Pool(max_threads) # how much parallelism? pool.map(run_process, arg_list) feeds = get_file_text(script_path()+"feed_urls.txt").split("\n") for i in list(feeds): if check_if_link(i) is False: feeds.remove(i) target_files = collect_links(feeds) multithreaded_process(target_files, download_file)
{ "repo_name": "CodyKochmann/rss_vault", "path": "run.py", "copies": "1", "size": "4096", "license": "mit", "hash": -8954793643966664000, "line_mean": 30.5076923077, "line_max": 109, "alpha_frac": 0.5695800781, "autogenerated": false, "ratio": 3.710144927536232, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47797250056362317, "avg_score": null, "num_lines": null }
# 1. WAP to create and merge two list and then sort it wihtout function sort # 2. WAP to create list of number and sort even numbers using LIST COMPREHENSION # 3. WAP to calculate number of uppercase and lowercase from input string. l1=[] l2=[] a=int(input("Enter number of elements you want to enter in list 1: ")) b=int(input("Enter number of elements you want to enter in list 2: ")) for i in range(a): x=int(input("Enter List Element: ")) l1.append(x) for i in range(b): x=int(input("Enter List Element: ")) l2.append(x) l1.extend(l2) m=[] for i in range (len(l1)): m.append(min(l1)) l1.remove(min(l1)) m.extend(l1) print(m,end=" ") print("is your sorted list") #P2 l=[] a=int(input("Number of elements in the list: ")) for i in range(a): x=int(input("Enter List Element: ")) l.append(x) lee=[i for i in l if i%2==0] print("List of your even numbers is={evenlist}".format(evenlist=lee)) #P3 s=input("Enter any word string: ") cu=0 cl=0 for i in s: if i.isupper(): cu=cu+1 else: cl=cl+1 print("Number of lower case:",cl) print("Number of upper case:",cu)
{ "repo_name": "Akagi201/learning-python", "path": "list/practice3.py", "copies": "1", "size": "1261", "license": "mit", "hash": -8111531305823587000, "line_mean": 20.1228070175, "line_max": 80, "alpha_frac": 0.5812846947, "autogenerated": false, "ratio": 2.967058823529412, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4048343518229412, "avg_score": null, "num_lines": null }
# 1) What is a recursive function? # A function calls itself, meaning it will repeat itself when a certain line or a code is called. # 2) What happens if there is no base case defined in a recursive function? #It will recurse infinitely and maybe you will get an error that says your maximum recursion is reached. # 3) What is the first thing to consider when designing a recursive function? # You have to consider what the base case(s) are going to be because that is when and how your function will end and return something. # 4) How do we put data into a function call? # We put data into a function call by using parameters. # 5) How do we get data out of a function call? # We get data out of a function call by using parameters. #a1 = 8 #a2 = 8 #a3 = -1 #b1 = 2 #b2 = 2 #b3 = 4 #c1 = -2 #c2 = 4 #c3 = 45 #d1 = 6 #d2 = 8 #d3 = 4 #Programming #Write a script that asks the user to enter a series of numbers. #When the user types in nothing, it should return the average of all the odd numbers that were typed in. #In your code for the script, add a comment labeling the base case on the line BEFORE the base case. #Also add a comment label BEFORE the recursive case. #It is NOT NECESSARY to print out a running total with each user input. def avg_odd_numbers(sum_n=0, odd_n=0): n = raw_input("Next number: ") #Base Case if n == "": return "The average of all the odd numbers are {}".format(sum_n/odd_n) #Recursive Case else: if float(n) % 2 == 1: return avg_odd_numbers(sum_n + float(n), odd_n + 1) else: return avg_odd_numbers(sum_n, odd_n) print avg_odd_numbers()
{ "repo_name": "beth2005-cmis/beth2005-cmis-cs2", "path": "cs2quiz3.py", "copies": "1", "size": "1645", "license": "cc0-1.0", "hash": -6662969976070371000, "line_mean": 30.6346153846, "line_max": 134, "alpha_frac": 0.6899696049, "autogenerated": false, "ratio": 3.323232323232323, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4513201928132323, "avg_score": null, "num_lines": null }
from micropython import const import _onewire as _ow class OneWireError(Exception): pass class OneWire: SEARCH_ROM = const(0xf0) MATCH_ROM = const(0x55) SKIP_ROM = const(0xcc) def __init__(self, pin): self.pin = pin self.pin.init(pin.OPEN_DRAIN, pin.PULL_UP) def reset(self, required=False): reset = _ow.reset(self.pin) if required and not reset: raise OneWireError return reset def readbit(self): return _ow.readbit(self.pin) def readbyte(self): return _ow.readbyte(self.pin) def readinto(self, buf): for i in range(len(buf)): buf[i] = _ow.readbyte(self.pin) def writebit(self, value): return _ow.writebit(self.pin, value) def writebyte(self, value): return _ow.writebyte(self.pin, value) def write(self, buf): for b in buf: _ow.writebyte(self.pin, b) def select_rom(self, rom): self.reset() self.writebyte(MATCH_ROM) self.write(rom) def scan(self): devices = [] diff = 65 rom = False for i in range(0xff): rom, diff = self._search_rom(rom, diff) if rom: devices += [rom] if diff == 0: break return devices def _search_rom(self, l_rom, diff): if not self.reset(): return None, 0 self.writebyte(SEARCH_ROM) if not l_rom: l_rom = bytearray(8) rom = bytearray(8) next_diff = 0 i = 64 for byte in range(8): r_b = 0 for bit in range(8): b = self.readbit() if self.readbit(): if b: # there are no devices or there is an error on the bus return None, 0 else: if not b: # collision, two devices with different bit meaning if diff > i or ((l_rom[byte] & (1 << bit)) and diff != i): b = 1 next_diff = i self.writebit(b) if b: r_b |= 1 << bit i -= 1 rom[byte] = r_b return rom, next_diff def crc8(self, data): return _ow.crc8(data)
{ "repo_name": "micropython/micropython-esp32", "path": "drivers/onewire/onewire.py", "copies": "22", "size": "2432", "license": "mit", "hash": 9067405670282738000, "line_mean": 25.7252747253, "line_max": 82, "alpha_frac": 0.4921875, "autogenerated": false, "ratio": 3.7300613496932513, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
from micropython import const import _onewire as _ow class OneWireError(Exception): pass class OneWire: SEARCH_ROM = const(0xF0) MATCH_ROM = const(0x55) SKIP_ROM = const(0xCC) def __init__(self, pin): self.pin = pin self.pin.init(pin.OPEN_DRAIN, pin.PULL_UP) def reset(self, required=False): reset = _ow.reset(self.pin) if required and not reset: raise OneWireError return reset def readbit(self): return _ow.readbit(self.pin) def readbyte(self): return _ow.readbyte(self.pin) def readinto(self, buf): for i in range(len(buf)): buf[i] = _ow.readbyte(self.pin) def writebit(self, value): return _ow.writebit(self.pin, value) def writebyte(self, value): return _ow.writebyte(self.pin, value) def write(self, buf): for b in buf: _ow.writebyte(self.pin, b) def select_rom(self, rom): self.reset() self.writebyte(MATCH_ROM) self.write(rom) def scan(self): devices = [] diff = 65 rom = False for i in range(0xFF): rom, diff = self._search_rom(rom, diff) if rom: devices += [rom] if diff == 0: break return devices def _search_rom(self, l_rom, diff): if not self.reset(): return None, 0 self.writebyte(SEARCH_ROM) if not l_rom: l_rom = bytearray(8) rom = bytearray(8) next_diff = 0 i = 64 for byte in range(8): r_b = 0 for bit in range(8): b = self.readbit() if self.readbit(): if b: # there are no devices or there is an error on the bus return None, 0 else: if not b: # collision, two devices with different bit meaning if diff > i or ((l_rom[byte] & (1 << bit)) and diff != i): b = 1 next_diff = i self.writebit(b) if b: r_b |= 1 << bit i -= 1 rom[byte] = r_b return rom, next_diff def crc8(self, data): return _ow.crc8(data)
{ "repo_name": "pfalcon/micropython", "path": "drivers/onewire/onewire.py", "copies": "1", "size": "2436", "license": "mit", "hash": -9059079040850688000, "line_mean": 25.1935483871, "line_max": 82, "alpha_frac": 0.4913793103, "autogenerated": false, "ratio": 3.719083969465649, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47104632797656487, "avg_score": null, "num_lines": null }
import _onewire as _ow class OneWireError(Exception): pass class OneWire: SEARCH_ROM = 0xF0 MATCH_ROM = 0x55 SKIP_ROM = 0xCC def __init__(self, pin): self.pin = pin self.pin.init(pin.OPEN_DRAIN, pin.PULL_UP) def reset(self, required=False): reset = _ow.reset(self.pin) if required and not reset: raise OneWireError return reset def readbit(self): return _ow.readbit(self.pin) def readbyte(self): return _ow.readbyte(self.pin) def readinto(self, buf): for i in range(len(buf)): buf[i] = _ow.readbyte(self.pin) def writebit(self, value): return _ow.writebit(self.pin, value) def writebyte(self, value): return _ow.writebyte(self.pin, value) def write(self, buf): for b in buf: _ow.writebyte(self.pin, b) def select_rom(self, rom): self.reset() self.writebyte(self.MATCH_ROM) self.write(rom) def scan(self): devices = [] diff = 65 rom = False for i in range(0xFF): rom, diff = self._search_rom(rom, diff) if rom: devices += [rom] if diff == 0: break return devices def _search_rom(self, l_rom, diff): if not self.reset(): return None, 0 self.writebyte(self.SEARCH_ROM) if not l_rom: l_rom = bytearray(8) rom = bytearray(8) next_diff = 0 i = 64 for byte in range(8): r_b = 0 for bit in range(8): b = self.readbit() if self.readbit(): if b: # there are no devices or there is an error on the bus return None, 0 else: if not b: # collision, two devices with different bit meaning if diff > i or ((l_rom[byte] & (1 << bit)) and diff != i): b = 1 next_diff = i self.writebit(b) if b: r_b |= 1 << bit i -= 1 rom[byte] = r_b return rom, next_diff def crc8(self, data): return _ow.crc8(data)
{ "repo_name": "stinos/micropython", "path": "drivers/onewire/onewire.py", "copies": "14", "size": "2395", "license": "mit", "hash": -7932161086781865000, "line_mean": 25.0326086957, "line_max": 82, "alpha_frac": 0.4860125261, "autogenerated": false, "ratio": 3.718944099378882, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
from micropython import const import _onewire as _ow class OneWireError(Exception): pass class OneWire: SEARCH_ROM = const(0xf0) MATCH_ROM = const(0x55) SKIP_ROM = const(0xcc) def __init__(self, pin): self.pin = pin self.pin.init(pin.OPEN_DRAIN) def reset(self, required=False): reset = _ow.reset(self.pin) if required and not reset: raise OneWireError return reset def readbit(self): return _ow.readbit(self.pin) def readbyte(self): return _ow.readbyte(self.pin) def readinto(self, buf): for i in range(len(buf)): buf[i] = _ow.readbyte(self.pin) def writebit(self, value): return _ow.writebit(self.pin, value) def writebyte(self, value): return _ow.writebyte(self.pin, value) def write(self, buf): for b in buf: _ow.writebyte(self.pin, b) def select_rom(self, rom): self.reset() self.writebyte(MATCH_ROM) self.write(rom) def scan(self): devices = [] diff = 65 rom = False for i in range(0xff): rom, diff = self._search_rom(rom, diff) if rom: devices += [rom] if diff == 0: break return devices def _search_rom(self, l_rom, diff): if not self.reset(): return None, 0 self.writebyte(SEARCH_ROM) if not l_rom: l_rom = bytearray(8) rom = bytearray(8) next_diff = 0 i = 64 for byte in range(8): r_b = 0 for bit in range(8): b = self.readbit() if self.readbit(): if b: # there are no devices or there is an error on the bus return None, 0 else: if not b: # collision, two devices with different bit meaning if diff > i or ((l_rom[byte] & (1 << bit)) and diff != i): b = 1 next_diff = i self.writebit(b) if b: r_b |= 1 << bit i -= 1 rom[byte] = r_b return rom, next_diff def crc8(self, data): return _ow.crc8(data)
{ "repo_name": "Xykon/pycom-micropython-sigfox", "path": "esp8266/modules/onewire.py", "copies": "12", "size": "2430", "license": "mit", "hash": -887834777208866700, "line_mean": 25.7032967033, "line_max": 82, "alpha_frac": 0.4925925926, "autogenerated": false, "ratio": 3.7442218798151004, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0017588409437473674, "num_lines": 91 }
import _onewire as _ow class OneWireError(Exception): pass class OneWire: SEARCH_ROM = const(0xf0) MATCH_ROM = const(0x55) SKIP_ROM = const(0xcc) def __init__(self, pin): self.pin = pin self.pin.init(pin.OPEN_DRAIN) def reset(self): return _ow.reset(self.pin) def readbit(self): return _ow.readbit(self.pin) def readbyte(self): return _ow.readbyte(self.pin) def read(self, count): buf = bytearray(count) for i in range(count): buf[i] = _ow.readbyte(self.pin) return buf def writebit(self, value): return _ow.writebit(self.pin, value) def writebyte(self, value): return _ow.writebyte(self.pin, value) def write(self, buf): for b in buf: _ow.writebyte(self.pin, b) def select_rom(self, rom): self.reset() self.writebyte(MATCH_ROM) self.write(rom) def scan(self): devices = [] diff = 65 rom = False for i in range(0xff): rom, diff = self._search_rom(rom, diff) if rom: devices += [rom] if diff == 0: break return devices def _search_rom(self, l_rom, diff): if not self.reset(): return None, 0 self.writebyte(SEARCH_ROM) if not l_rom: l_rom = bytearray(8) rom = bytearray(8) next_diff = 0 i = 64 for byte in range(8): r_b = 0 for bit in range(8): b = self.readbit() if self.readbit(): if b: # there are no devices or there is an error on the bus return None, 0 else: if not b: # collision, two devices with different bit meaning if diff > i or ((l_rom[byte] & (1 << bit)) and diff != i): b = 1 next_diff = i self.writebit(b) if b: r_b |= 1 << bit i -= 1 rom[byte] = r_b return rom, next_diff def crc8(self, data): return _ow.crc8(data) class DS18B20: CONVERT = const(0x44) RD_SCRATCH = const(0xbe) WR_SCRATCH = const(0x4e) def __init__(self, onewire): self.ow = onewire def scan(self): return [rom for rom in self.ow.scan() if rom[0] == 0x28] def convert_temp(self): if not self.ow.reset(): raise OneWireError self.ow.writebyte(SKIP_ROM) self.ow.writebyte(CONVERT) def read_scratch(self, rom): if not self.ow.reset(): raise OneWireError self.ow.select_rom(rom) self.ow.writebyte(RD_SCRATCH) buf = self.ow.read(9) if self.ow.crc8(buf): raise OneWireError return buf def write_scratch(self, rom, buf): if not self.ow.reset(): raise OneWireError self.ow.select_rom(rom) self.ow.writebyte(WR_SCRATCH) self.ow.write(buf) def read_temp(self, rom): buf = self.read_scratch(rom) return (buf[1] << 8 | buf[0]) / 16
{ "repo_name": "misterdanb/micropython", "path": "esp8266/scripts/onewire.py", "copies": "8", "size": "3338", "license": "mit", "hash": 1354741967146086000, "line_mean": 25.2834645669, "line_max": 82, "alpha_frac": 0.5068903535, "autogenerated": false, "ratio": 3.521097046413502, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0017852062405328904, "num_lines": 127 }
# 1. Write a function called common_end() that takes two lists. # It will return True if the two lists either have the same # first element, the same LAST element, or both. # common_end([1,2,3], [7,3]) ---> True # common_end([1,2,3], [7,3,2]) ---> False # common_end([1,2,3], [1,7]) ---> True def common_end(list1, list2): if list1[0] == list2[0]: return True elif list1[-1] == list2[-1]: return True else: return False # 2. Write a function called list_product() that takes a list. # It returns the product of all the numbers in the list. # list_product([1,2,3,4,5]) ---> 120 # list_product([8,4,3]) ---> 96 # list_product([120, 57, 98, 0, 12]) ---> 0 def list_product(num_list): total = 1 for number in num_list: total *= number return total # 3. Write a function called rotate_left() that takes a list # and rotates all the elements in the list one space to # the left (Hint: no loop necessary!) # # rotate_left([1,2,3]) ---> [2,3,1] # rotate_left(['this', 'is', 'a', 'sentence']) ---> # ['is', 'a', 'sentence', 'this'] def rotate_left(lst): first = lst.pop(0) #Defaults to LAST ENTRY IN LIST lst.append(first) return lst # 4. Write a function called count_evens() that takes a list # of numbers and returns the count of the number of even # numbers in that list. Hint: To see if a number is even, # check if the remainder when dividing by 2 is 0...x%2==0 # count_evens([2,1,2,3,4]) ---> 3 # count_evens([1,3,5,7,9]) ---> 0 # count_evens([2,4,6,8,10,12]) ---> 6 def count_evens(num_list): count = 0 for number in num_list: if number % 2 == 0: count += 1 return count # 5. Write a function called list_range() that takes a list # of numbers and returns the range of the list, which is # the largest number minus the smallest number. # Hint: You can do this with a for loop, but there's actually # a built in way to get the largest or smallest number in # a list...try Googling! # list_range([10, 3, 5, 4, 6]) ---> 7 # list_range([7,2,10, 9)] ---> 8 # list_range([2, 10, 7, 2]) ---> 8 # list_range([]) ---> 0 #No Google def list_range(num_list): num_list.sort() if num_list == []: return 0 return num_list[-1] - num_list[0] #Using Google def list_range2(num_list): if num_list == []: return 0 return max(num_list) - min(num_list) # 6. Write a function called no_a() that takes a list # of words and returns a new list that contains only # the words that DON'T have an 'a' in them. # no_a(['apple', 'banana', 'grape', 'kiwi', 'mango', 'coconut']) # ---> ['kiwi', 'coconut'] # no_a(['Africa', 'Europe', 'Asia', 'Antarctica', 'South America', 'North America', 'Australia'] # ---> ['Europe'] #My version def no_a(lst): no_a_list = [] for word in lst: original_word = word word = word.lower() num_a = word.count('a') if num_a == 0: no_a_list.append(original_word) return no_a_list #The official version def no_a2(lst): new_list = [] for word in lst: if 'a' not in word.lower(): new_list.append(word) return new_list # CHALLENGE: Write a function called has_duplicates() # that takes a list and returns True if there is ANY # element in the list that repeats. def no_duplicates(lst): for entry in lst: if lst.count(entry) > 1: return False return True
{ "repo_name": "Nethermaker/school-projects", "path": "intro/list_and_for_loop_assignment.py", "copies": "1", "size": "3707", "license": "mit", "hash": -3739872054988869600, "line_mean": 21.16875, "line_max": 96, "alpha_frac": 0.5600215808, "autogenerated": false, "ratio": 3.0211898940505297, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9043759556197444, "avg_score": 0.007490383730617145, "num_lines": 160 }
# A flexible object to redirect standard output and standard error # Allows logging to a file and to set a level of verbosity # Copyright Michael Foord, 2004. # Released subject to the BSD License # Please see http://www.voidspace.org.uk/python/license.shtml # For information about bugfixes, updates and support, please join the Pythonutils mailing list. # http://groups.google.com/group/pythonutils/ # Comments, suggestions and bug reports welcome. # Scripts maintained at http://www.voidspace.org.uk/python/index.shtml # E-mail fuzzyman@voidspace.org.uk """ StandOut - the Flexible Output Object (FOO !) Adds optional logging to a file and setting of verbosity levels to the stdout stream This means that, for the most part, standard print statments can be used throughout your program and StandOut handles the rest. Your user can choose a 'verbosity' level (how much information they want to receive), you give your messages a priority level, and only messages with a high enough priority are actually displayed. A simple way of implementing varying degrees of verbosity. Additionally the output can be captured to a log file with no extra work. (simply pass in a filename when you craete the object and anything printed is sent to the file as well) StandOut can now be used with sys.stderr as well as sys.stdout. This includes logging both sys.stdout *and* sys.stderr to the same file. See the sys.stderr section at the bottom of this. SIMPLE USAGE (also see the tests which illustrate usage). stout = StandOut(verbosity=verbositylevel) or to log to a file : stout = StandOut(filename='log.txt') The verbosity level can be changed at any time by setting stout.verbosity : stout.verbosity = 6 The priority of messages defaults to 5. This can be changed by setting stout.priority = 6 *or* print '&priority-6;' The priority of an individual line can be set by *starting* the line with a priority marker : print '&priority-6;This text has a priority 6.' *or* by using the stout.write() method with a priority value: stout.write('This text has a priority 6.\n', 6) (notice you must add the '\n' when using the stout.write method.) Only messages with a priority equal to or greater than the current verbosity level will be printed. e.g. if stout.verbosity = 6 (or the stout object was created using stout=StandOut(verbosity=6) ) Only messages with a priority of 6 or above will be printed. stout.write('This won't get printed\n, 5) print '&priority-4;Nor will this' stout.write('But this will\n', 6) print '&priority-7;And so will this' If for *any* reason you want to *actually* print a '&priority-n' marker at the start of a line then you can escape it with a '&priority-e;' : print '&priority-e;&priority-1;' will actually print : &priority-1; StandOut will log to a file as well. Set this by passing in a filename=filename keyword when you create the object *or* by setting stout.filename at any time. The file has it's own priority, stout.file_verbosity. Again this can be set when the object is created and/or changed at any time. See the full docs below. This means your user can set a verbosity level (at the command line probably), you give each message a priority setting and just use normal print statements in your program. Only messages above your user's setting are actually displayed. You can also set the log file to have a different priority threshhold to what is printed to the screen. (So either less or more is logged to the file than is displayed at runtime.) You can also pass in another function which can be used to display messages with (e.g. to a GUI window or whatever). It also has it's own priority setting. Any output method can be silenced by setting it to 0 All output can be silenced by setting the priority to 0 The stdout stream can be restored and any log file closed by calling stout.close() verbosity = 1 is the highest verbosity = 9 is the lowest (only messages of priority 9 are printed) verbosity = 0 is special - it switches off printing altogether LIST OF KEYWORDS AND METHODS StandOut Possible keyword arguments (with defaults shown) are : (The following keywords also map to attributes of the StandOut object which can be read or set) priority = 5 verbosity = 5 filename = None file_verbosity = 5 file_mode = 'w' print_fun = None printfun_verbosity = 5 Keyword arguments should either be passed in as a dictionary *or* as keywords when the object is created. If a dictionary is passed in, any other keywords will be ignored. Any missing keywords will use the defaults. Methods ( stout = StandOut() ): stout.close() stout.write(line, priority) stout.set_print(function) stout.setall(verbosity) the original stdout can be reached using : stout.output.write() **NOTE** normal print statements make two calls to stdout.write(). Once for the text you are printing and another for the trailing '\n' or ' '. StandOut captures this to make sure the trailing '\n' or ' ' is printed at the same priority as the original line. This means you shouldn't use stout.write(line) where line uses the '&priority-n;' markers. (Because stout.write(line) only makes one call, not two). Either call stout.write(line, priority) to set a priority for that line. *or* set stout.priority directly. EXPLANATION OF KEYWORDS AND METHODS priority = 5 This sets the priority for messages. If priority is 5 - then only output methods with a 'verbosity' of 5 or lower will display them. This value can later be set by adjusting the stout.priority attribute or using the priority markers. verbosity = 5 This is the verbosity level for messages to be printed to the screen. If the verbosity is 5 then only messages with a priority of 5 or higher will be sent to the screen. (Like a normal print statement). You can nadjust this at stout.verbosity filename = None If you pass in a filename when you create the object it will be used as a logfile. It has it's own 'verbosity' level called 'file_verbosity'. If you don't pass in a filename, you can later add one by setting stout.filename Changing stout.filename after you have already set one is a bad thing to do :-) file_verbosity = 5 This is the verbosity level of the log file. Only messages with a priority higher than this will be sent to the logfile. print_fun = None If you pass in a function (that takes one parameter - the line to be printed) this will be used to print as well. The function *isn't* stored at stout.print_fun - this value is just set to True to say we have a function. This could be used for displaying to the output window of a GUI, for example. If you want to pass in a function after obect creation then use the stout.set_print(function) method. You musn't have print statements in your function or you will get stuck in a loop (call stout.output.write(line) instead) printfun_verbosity = 5 Any function you pass in also has it's own verbosity setting - printfun_verbosity. stream = 'output' By default StandOut will divert the sys.stdout stream. Set to 'error' to divert the sys.stderr share = False You can divert both sys.stdout and sys.stderr. You can log both to the same file. Set a filename for your sys.stdout object and set share = True for your sys.stderr object. Any lines sent to sys.stderr will have a prefix attached to them. See 'error_marker' error_marker = '[err] ' This is the marker put before every line logged from sys.stderr. It only applies if share is on - this means both streams are logged to the same file. stout.close() When your program has finished with the obejct it should call stout.close() which restores sy.stdout and closes any logfile we have been using. stout.write(line, priority) This can be used as an alternative way of specifying a priority for an individual line. It leaves stout.priority unaffected. Any calls to stout.write must have '\n' at the end if you want it to end with a newline. If you don't specify a priority then it behaves like sys.stdout.write would. Don't use priority markers with this and method and you can't use priority = 0 (the priority setting will be ignored) stout.set_print(function) This is used to pass in an additional printing function after the object has been created. stout.setall(verbosity) Thisis a quick way of changing the verbosity for all three output methods. Setting verbosity, file_verbosity or printfun_verbosity to 0 disables that ouput method. Setting priority to 0 switches off all output. If you want to print to stdout directly and bypass the stout object for any reason - it is saved at stout.output Calls to stout.output.write(line) have the same effect that sys.stdout.write(line) would have had. PRIORITY MARKERS As well as directly setting stout.priority and using stout.write(line, priority) You can set the priority of a individual line *or* change the general priority setting just using print statements. This is using 'priority markers'. print '&priority-n;' # sets the priority to n, where n is 0-9 print '&priority-n;The stuff to print' # sets the priority of just that line to n If you actually want to print '&priority-n;' at the start of a line then you should escape it by putting '&priority-e;' in front of it. '&priority-e;' can also be escaped in the same way ! Don't use priority markers if you are making direct calls to stout.write() use stout.write(line, priority) to set the priority of an individual line or alter stout.priority to adjust the general priority. sys.stderr StandOut can now be used to divert sys.stderr as well as sys.stdout. To create an output object that does for sys.stderr *exactly* the same as we would do for sys.stdout use : stout2 = StandOut(stream='error') It can log to a file and has all the properties that we had for sys.stdout. If you wanted to log to the *same* file as you are using for sys.stdout you *can't* just pass it the same filename. The two objects would both try to have a write lock on the same file. What you do is pass the 'share' keyword to the error object when you create it : stout = StandOut(filename='log.txt') stout2 = StandOut(stream='error', share=True) Anything sent to sys.stdout *or* sys.stderr will now be logged in the 'log.txt' file. Every line sent to sys.stderr will be prefixed with '[err] ' which is the default error marker. You can adjust this with the 'error_marker' keyword. stout2 = StandOut(stream='error', share=True, error_marker='**ERROR** ') """ __all__ = ['StandOut'] import sys class StandOut: stdout = None stderr = None def __init__(self, indict=None, **keywargs): """StandOut - the Flexible Output Object (FOO !)""" if indict is None: indict = {} # defaults = { 'priority': 5, 'verbosity': 5, 'filename': None, 'file_verbosity': 5, 'file_mode': 'w', 'print_fun': None, 'printfun_verbosity': 5 , 'stream': 'output', 'share': False, 'error_marker': '[err] ' } # if not indict: indict = keywargs for value in defaults: if not indict.has_key(value): indict[value] = defaults[value] # if indict['stream'].lower() == 'error': self.output = sys.stderr sys.stderr = StandOut.stderr = self self.stream = indict['stream'].lower() else: self.output = sys.stdout sys.stdout = StandOut.stdout = self self.stream = indict['stream'].lower() self.filename = indict['filename'] if self.filename: self.filehandle = file(self.filename, indict['file_mode']) else: self.filehandle = None self.file_mode = indict['file_mode'] self.share = indict['share'] self.err_marker = indict['error_marker'] self.done_linefeed = True self.priority = indict['priority'] # current message priority self.file_verbosity = indict['file_verbosity'] # file output threshold self.verbosity = indict['verbosity'] # stdout threshhold self.printfun_verbosity = indict['printfun_verbosity'] # print_fun threshold if indict['print_fun']: # set up the print_fun if we have been given one self.print_fun = True self.thefun = [indict['print_fun']] else: self.print_fun = False self.markers = {} for num in range(10): # define the markers thismarker = '&priority-' + str(num) + ';' self.markers[thismarker] = num self.escapemarker = '&priority-e;' self.skip = 0 self._lastpriority = 0 ######################################################################### # public methods - available as methods of any instance of StandOut you create def write(self, line, priority = 0): """Print to any of the output methods we are using. Capture lines which set priority.""" if self.skip: # if the last line was a priority marker then self.skip is set and we should miss the '\n' or ' ' that is sent next self.skip = 0 return if not priority: if self._lastpriority: # if the last line had a priority marker at the start of it, then the '\n' or ' ' that is sent next should have the same priority priority = self._lastpriority self._lastpriority = 0 else: priority = self.priority if line in self.markers: # if the line is a priority marker self.skip = 1 # either a '\n' or a ' ' will now be sent to sys.stdout.write() by print self.priority = self.markers[line] return if line[:12] in self.markers: # if the line starts with a priority marker priority = int(line[10]) # the priority of this line is at position 10 self._lastpriority = priority # set this value so that the '\n' or ' ' that follows also has the same priority line = line[12:] # chop off the marker elif line[:12] == self.escapemarker: line = line[12:] # this just removes our 'escape marker' if not priority: # if priority is set to 0 then we mute all output return if self.filename and not self.filehandle: # if a filename has been added since we opened self.filehandle = file(self.filename, self.file_mode) if self.filehandle and self.file_verbosity and priority >= self.file_verbosity: # if we have a file and file_verbosity is high enough to output self.filehandle.write(line) if self.verbosity and priority >= self.verbosity: # if verbosity is set high enough we print if self.share and self.stream == 'error' and hasattr(StandOut.stdout, 'filename'): # if we are the error stream *and* share is on *and* stdout has a filename attribute.. if self.done_linefeed: StandOut.stdout.filehandle.write(self.err_marker) self.done_linefeed = False if line.endswith('\n'): self.done_linefeed = True line = line[:-1] line = line.replace('\n', '\n' + self.err_marker) if self.done_linefeed: line = line + '\n' StandOut.stdout.filehandle.write(line) # if 'share' is on we log to stdout file as well as print # StandOut.stdout.output.write('hello') self.output.write(line) # if we have a print function set and it's priority is high enough if self.print_fun and self.printfun_verbosity and priority >= self.printfun_verbosity: self.use_print(line) def close(self): """Restore the stdout stream and close the logging file if it's open.""" if self.stream == 'error': sys.stderr = self.output else: sys.stdout = self.output if self.filename and self.filehandle: self.filehandle.close() del self.filehandle def set_print(self, print_fun): """Set a new print_fun.""" self.print_fun = True self.thefun = [print_fun] def setall(self, verbosity): """Sets the verbosity level for *all* the output methods.""" self.verbosity = self.file_verbosity = self.printfun_verbosity = verbosity def flush(self): return self.output.flush() def writelines(self, inline): for line in inlines: self.write(line) def __getattr__(self, attribute): if not self.__dict__.has_key(attribute) or attribute == '__doc__': return getattr(self.output, attribute) return self.__dict__[attribute] ########################################################## # private methods, you shouldn't need to call these directly def use_print(self, line): """A wrapper function for the function passed in as 'print_fun'.""" self.thefun[0](line) if __name__ == '__main__': test = StandOut() print 'hello' test.priority = 4 print "You shouldn't see this" test.verbosity = 4 print 'You should see this' test.priority = 0 print 'but not this' test.write('And you should see this\n', 5) print 'but not this' test.filename = 'test.txt' test.priority = 5 test.setall(5) print 'This should go to the file test.txt as well as the screen.' test.file_verbosity = 7 print '&priority-8;' print 'And this should be printed to both' print '&priority-6;But this should only go to the screen.' print 'And this should be printed to both, again.' def afunction(line): test.output.write('\nHello\n') test.set_print(afunction) print "We're now using another print function - which should mirror 'hello' to the screen." print "In practise you could use it to send output to a GUI window." print "Or perhaps format output." test2 = StandOut(stream='error', share=True) # anything printed to sys.stderr, should now be logged to the stdout file as well sys.stderr.write('Big Mistake') sys.stderr.write('\n') sys.stderr.write('Another Error') sys.stderr.write('\n') test.close() test2.close() print 'Normality is now restored' print 'Any further problems, are entirely your own.' """ ISSUES/TODO =========== Doctests Could trap when stout.write(line) is used with a priority marker. (By checking for the default value of priority). Could add a ``both`` keyword argument to avoid having to use the `share`` keyword argument. It can just instantiate another StandOut itself. CHANGELOG ========= 2005/01/06 Version 2.1.0 Added flush and writelines method. Added the 'stream' keyword for diverting the sys.stderr stream as well. Added __getattr__ for any undefined methods. Added the 'share' and 'error_marker' keywords for logging sys.stderr to the same file as sys.stdout. 07-04-04 Version 2.0.0 A complete rewrite. It now redirects the stdout stream so that normal print statements can be used. Much better. 06-04-04 Version 1.1.0 Fixed a bug in passing in newfunc. Previously it only worked if you had a dummy variable for self. """
{ "repo_name": "cligu/gitdox", "path": "modules/standout.py", "copies": "2", "size": "19719", "license": "apache-2.0", "hash": 8628892551416264000, "line_mean": 40.8662420382, "line_max": 186, "alpha_frac": 0.6725493179, "autogenerated": false, "ratio": 3.9828317511613816, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5655381069061381, "avg_score": null, "num_lines": null }
# A simple proxy server that fetches pages from the google cache. # Homepage : http://www.voidspace.org.uk/python/index.html # Copyright Michael Foord, 2004 & 2005. # Released subject to the BSD License # Please see http://www.voidspace.org.uk/documents/BSD-LICENSE.txt # For information about bugfixes, updates and support, please join the Pythonutils mailing list. # http://voidspace.org.uk/mailman/listinfo/pythonutils_voidspace.org.uk # Comments, suggestions and bug reports welcome. # Scripts maintained at http://www.voidspace.org.uk/python/index.shtml # E-mail fuzzyman@voidspace.org.uk """ This is a simple implementation of a proxy server that fetches web pages from the google cache. It is based on SimpleHTTPServer. It lets you explore the internet from your browser, using the google cache. See the world how google sees it. Alternatively - retro internet - no CSS, no javascript, no images, this is back to the days of MOSAIC ! Run this script and then set your browser proxy settings to localhost:8000 Needs google.py (and a google license key). See http://pygoogle.sourceforge.net/ and http://www.google.com/apis/ Tested on Windows XP with Python 2.3 and Firefox/Internet Explorer Also reported to work with Opera/Firefox and Linux Because the google api will only allow 1000 accesses a day we limit the file types we will check for. A single web page may cause the browser to make *many* requests. Using the 'cached_types' list we try to only fetch pages that are likely to be cached. We *could* use something like scraper.py to modify the HTML to remove image/script/css URLs instead. Some useful suggestions and fixes from 'vegetax' on comp.lang.python """ import google import BaseHTTPServer import shutil from StringIO import StringIO # cStringIO doesn't cope with unicode import urlparse __version__ = '0.1.0' cached_types = ['txt', 'html', 'htm', 'shtml', 'shtm', 'cgi', 'pl', 'py' 'asp', 'php', 'xml'] # Any file extension that returns a text or html page will be cached google.setLicense(google.getLicense()) googlemarker = '''<i>Google is not affiliated with the authors of this page nor responsible for its content.</i></font></center></td></tr></table></td></tr></table>\n<hr>\n''' markerlen = len(googlemarker) import urllib2 # uncomment the next three lines to over ride automatic fetching of proxy settings # if you set localhost:8000 as proxy in IE urllib2 will pick up on it # you can specify an alternate proxy by passing a dictionary to ProxyHandler ##proxy_support = urllib2.ProxyHandler({}) ##opener = urllib2.build_opener(proxy_support) ##urllib2.install_opener(opener) class googleCacheHandler(BaseHTTPServer.BaseHTTPRequestHandler): server_version = "googleCache/" + __version__ cached_types = cached_types googlemarker = googlemarker markerlen = markerlen txheaders = { 'User-agent' : 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)' } def do_GET(self): f = self.send_head() if f: self.copyfile(f, self.wfile) f.close() def send_head(self): """Only GET implemented for this. This sends the response code and MIME headers. Return value is a file object, or None. """ print 'Request :', self.path # traceback to sys.stdout url_tuple = urlparse.urlparse(self.path) url = url_tuple[2] domain = url_tuple[1] if domain.find('.google.') != -1: # bypass the cache for google domains req = urllib2.Request(self.path, None, self.txheaders) self.send_response(200) self.send_header("Content-type", 'text/html') self.end_headers() return urllib2.urlopen(req) dotloc = url.rfind('.') + 1 if dotloc and url[dotloc:] not in self.cached_types: return None # not a cached type - don't even try print 'Fetching :', self.path # traceback to sys.stdout thepage = google.doGetCachedPage(self.path) # XXXX should we check for errors here ? headerpos = thepage.find(self.googlemarker) if headerpos != -1: pos = self.markerlen + headerpos thepage = thepage[pos:] f = StringIO(thepage) # turn the page into a file like object self.send_response(200) self.send_header("Content-type", 'text/html') self.send_header("Content-Length", str(len(thepage))) self.end_headers() return f def copyfile(self, source, outputfile): shutil.copyfileobj(source, outputfile) def test(HandlerClass = googleCacheHandler, ServerClass = BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass) if __name__ == '__main__': test()
{ "repo_name": "ActiveState/code", "path": "recipes/Python/408991_GoogleCacheServer/recipe-408991.py", "copies": "1", "size": "4874", "license": "mit", "hash": 8650231299246874000, "line_mean": 35.9242424242, "line_max": 175, "alpha_frac": 0.6844480919, "autogenerated": false, "ratio": 3.7262996941896023, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9866239419960992, "avg_score": 0.008901673225721989, "num_lines": 132 }
"""20.07.2015 PyOSE: Stacked exomoons with the Orbital Sampling Effect.""" import PyOSE import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib import rc from numpy import pi # Set stellar parameters StellarRadius = 0.7 * 696342. # km limb1 = 0.5971 limb2 = 0.1172 # Set planet parameters PlanetRadius = 6371 * 4.8 PlanetAxis = 0.1246 * 149597870.700 # [km] PlanetImpact = 0.25 # [0..1.x]; central transit is 0. PlanetPeriod = 16.96862 # [days] # Set moon parameters MoonRadius = 6371 * 0.7 # [km] MoonAxis = 238912.5 # [km] <<<<------ MoonEccentricity = 0.0 # 0..1 MoonAscendingNode = -30.0 # degrees MoonLongitudePeriastron = 50.0 # degrees MoonInclination = 83.0 # 0..90 in degrees. 0 is the reference plain (no incl). # Set other parameters ShowPlanetMoonEclipses = True # True: the reality; False would be no mutual # eclipses. Of course unphysical, but useful for tests and comparisons) ShowPlanet = False # True: Planet+Moon; False: Moon only Noise = 0 # [ppm per minute]; 0 = no noise is added NumberOfTransits = 0 # How many (randomly chosen) transits are observed; # if 0 then all available are sampled (and their number is 10*Quality). PhaseToHighlight = 0.2 # If no highlighting is desired, choose value < 0 Quality = 250 # Radius of star in pixels --> size of numerical sampling grid NumberOfSamples = 250 # How many transits are to be sampled # Curve MyNewCurve = PyOSE.curve(StellarRadius, limb1, limb2, PlanetRadius, PlanetAxis, PlanetImpact, PlanetPeriod, MoonRadius, MoonAxis, MoonEccentricity, MoonAscendingNode, MoonLongitudePeriastron, MoonInclination, ShowPlanetMoonEclipses, ShowPlanet, Quality, NumberOfSamples, Noise, NumberOfTransits) Time = MyNewCurve[0][1:] Flux = MyNewCurve[1][1:] ax = plt.axes() plt.plot(Time, Flux, color = 'k') plt.rc('text', usetex=True) plt.rc('font', family='serif') plt.tick_params(axis='both', which='major', labelsize=16) plt.xlabel('time around planetary mid-transit [days]',fontsize=16) plt.ylabel('normalized stellar brightness [ppm]',fontsize=16) plt.axis([-0.2, +0.2, -100, 1], set_aspect='equal', fontsize=16) ax.tick_params(direction='out') MoonAxis = 61162 MyNewCurve = PyOSE.curve(StellarRadius, limb1, limb2, PlanetRadius, PlanetAxis, PlanetImpact, PlanetPeriod, MoonRadius, MoonAxis, MoonEccentricity, MoonAscendingNode, MoonLongitudePeriastron, MoonInclination, ShowPlanetMoonEclipses, ShowPlanet, Quality, NumberOfSamples, Noise, NumberOfTransits) Time = MyNewCurve[0][1:] Flux = MyNewCurve[1][1:] plt.plot(Time, Flux, color = 'k') plt.annotate(r"$a_{s} = 0.5 R_{\rm H}$ ", xy=(0.08, -40), size=16) plt.annotate(r"$a_{s} = 0.128 R_{\rm H}$ ", xy=(-0.06, -20), size=16) plt.savefig("fig_8a.pdf", bbox_inches='tight') #plt.savefig("fig_8a.eps", bbox_inches='tight') plt.show()
{ "repo_name": "hippke/PyOSE", "path": "CreateFigure8a.py", "copies": "1", "size": "2836", "license": "mit", "hash": 7197681053772878000, "line_mean": 36.8133333333, "line_max": 80, "alpha_frac": 0.7175599436, "autogenerated": false, "ratio": 2.7507274490785645, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39682873926785645, "avg_score": null, "num_lines": null }
"""20.07.2015 PyOSE: Stacked exomoons with the Orbital Sampling Effect.""" import PyOSE import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib import rc #import xlwt #from tempfile import TemporaryFile from numpy import pi # Set stellar parameters StellarRadius = 0.7 * 696342. # km limb1 = 0.5971 limb2 = 0.1172 # Set planet parameters #PlanetRadius = 63700. # [km] PlanetRadius = 6371 * 4.8 PlanetAxis = 0.1246 * 149597870.700 # [km] PlanetImpact = 0.0# 0.25 # [0..1.x]; central transit is 0. PlanetPeriod = 16.96862 # [days] # Set moon parameters MoonRadius = 6371 * 0.7 # [km] #MoonAxis = 15.47 * 4.8 * 6371 # [km] MoonAxis = 238912.5 # [km] <<<<------ #Hill radius 75 * 6371, 477825 - limit 0.5 Hill --> 238912.5 #Roche lobe 2 * 6371 * 4.8 = 61162 MoonEccentricity = 0.0 # 0..1 MoonAscendingNode = 0.0 # degrees MoonLongitudePeriastron = 50.0 # degrees MoonInclination = 83.0 # 0..90 in degrees. 0 is the reference plain (no incl). # Set other parameters ShowPlanetMoonEclipses = True # True: the reality; False would be no mutual # eclipses. Of course unphysical, but useful for tests and comparisons) ShowPlanet = False # True: Planet+Moon; False: Moon only Noise = 0 # [ppm per minute]; 0 = no noise is added NumberOfTransits = 0 # How many (randomly chosen) transits are observed; # if 0 then all available are sampled (and their number is 10*Quality). PhaseToHighlight = 0.2 # If no highlighting is desired, choose value < 0 Quality = 250 # Radius of star in pixels --> size of numerical sampling grid NumberOfSamples = 250 # How many transits are to be sampled # Curve PlanetImpact = 0.25# 0.25 # [0..1.x]; central transit is 0. MoonInclination = 90.0 # 0..90 in degrees. 0 is the reference plain (no incl). MoonRadius = 6371 * 0.7 # [km] MoonAxis = 61162 # [km] <<<<------0.5 Hill MyNewCurve = PyOSE.curve(StellarRadius, limb1, limb2, PlanetRadius, PlanetAxis, PlanetImpact, PlanetPeriod, MoonRadius, MoonAxis, MoonEccentricity, MoonAscendingNode, MoonLongitudePeriastron, MoonInclination, ShowPlanetMoonEclipses, ShowPlanet, Quality, NumberOfSamples, Noise, NumberOfTransits) Time1 = MyNewCurve[0][1:] Flux1 = MyNewCurve[1][1:] ax = plt.axes() plt.plot(Time1, Flux1, color = 'k') plt.rc('text', usetex=True) plt.rc('font', family='serif') plt.tick_params(axis='both', which='major', labelsize=16) plt.xlabel('time around planetary mid-transit [days]',fontsize=16) plt.ylabel('normalized stellar brightness [ppm]',fontsize=16) plt.axis([-0.2, +0.2, -100, 1], set_aspect='equal', fontsize=16) ax.tick_params(direction='out') MoonRadius = 6371 * 0.35 # [km] MoonAxis = 238912.5 # [km] <<<<------ MyNewCurve = PyOSE.curve(StellarRadius, limb1, limb2, PlanetRadius, PlanetAxis, PlanetImpact, PlanetPeriod, MoonRadius, MoonAxis, MoonEccentricity, MoonAscendingNode, MoonLongitudePeriastron, MoonInclination, ShowPlanetMoonEclipses, ShowPlanet, Quality, NumberOfSamples, Noise, NumberOfTransits) Time2 = MyNewCurve[0][1:] Flux2 = MyNewCurve[1][1:] plt.plot(Time2, Flux2, color = 'k') summe = Flux1+Flux2 plt.plot(Time2, summe, color = 'k', linestyle='dashed', linewidth=2) plt.savefig("fig_11.pdf", bbox_inches='tight') plt.show()
{ "repo_name": "hippke/PyOSE", "path": "CreateFigure11.py", "copies": "1", "size": "3248", "license": "mit", "hash": 4166175099531349500, "line_mean": 32.8333333333, "line_max": 80, "alpha_frac": 0.7090517241, "autogenerated": false, "ratio": 2.708924103419516, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3917975827519516, "avg_score": null, "num_lines": null }
"""20.07.2015 PyOSE: Stacked exomoons with the Orbital Sampling Effect.""" # Stacked exomoons with the Orbital Sampling Effect (OSE, Heller 2014, ApJ 787) # # _.--"~~ __"-. Copyright 2015 Michael Hippke and contributors # ,-" .-~ ~"-\ OSE-Sampler is free software # .^ / ( ) made available under the MIT License # {_.---._ / ~ http://opensource.org/licenses/MIT # / . Y # / \_j # Y ( --l__ # | "-. # | (___ \ If you make use of OSE-Sampler in your work, # | .)~-.__/ please cite our paper: # l _) Hippke & Heller 2015, arXiv, ADS, BibTeX # \ "l # \ \ # \ ^. # ^. "-. # "-._ ~-.___, # "--.._____.^ # # Contributors: Add your name here if you like # Michael Hippke - initiator # Rene Heller - requirements and OSE Theory (Heller 2014, ApJ 787) # Stefan Czesla - conversion of some functions from Pascal to Python import matplotlib.pylab as plt import numpy as np from numpy import pi, sqrt, sin, cos, arcsin, arccos, radians, power, degrees from PyAstronomy import pyasl from PyAstronomy.modelSuite import forTrans from matplotlib.pyplot import cm def modelview( StellarRadius, limb1, limb2, PlanetRadius, PlanetImpact, MoonRadius, MoonAxis, MoonEccentricity, MoonAscendingNode, MoonLongitudePeriastron, MoonInclination, PhaseToHighlight, Quality): """Calculate the 3D model view. This is the vector version (v2)""" # Convert values from km to internal measure (stellar radius = 1) PlanetRadius = PlanetRadius / StellarRadius MoonRadius = MoonRadius / StellarRadius MoonAxis = MoonAxis / StellarRadius # Make background unicolor black or white #allwhite = plt.Circle((0, 0), 100, color=(1, 1, 1)) #allblack = plt.Circle((0, 0), 100, color=(0, 0, 0)) #plt.gcf().gca().add_artist(allwhite) # Alternatively plot a gradient map as background X = [[-1, 0], [0, 1]] plt.imshow(X, interpolation='bicubic', cmap=cm.gray, extent=(-1.1, 1.1, -1.1, 1.1), alpha=1) # Star StarQuality = Quality StarQuality = 100 for i in range(StarQuality): Impact = i / float(StarQuality) LimbDarkening = QuadraticLimbDarkening(Impact, limb1, limb2) Sun = plt.Circle((0, 0), 1 - i / float(StarQuality), color=(LimbDarkening, LimbDarkening, LimbDarkening)) # for a yellow shaded star, replace the last LimbDarkening with 0 plt.gcf().gca().add_artist(Sun) # Moon's orbit: Kepler ellipse normalized to 1x1 stellar radii Ellipse = pyasl.KeplerEllipse( MoonAxis, MoonAxis, e = MoonEccentricity, Omega = MoonAscendingNode, w = MoonLongitudePeriastron, i = MoonInclination) NumerOfSamples = 1 / float(Quality) time = np.linspace(0., MoonAxis, Quality) coordinates = np.zeros((len(time), 3), dtype=np.float) for i in xrange(len(time)): coordinates[i,::] = Ellipse.xyzPos(time[i]) OccultedDataPoints = [] # To clip the moon ellipse "behind" the planet for i in range(Quality / 2): CurrentMoonImpact = coordinates[i, 1] CurrentHorizontalMoonPosition = coordinates[i, 0] CurrentDistanceMoonPlanet = sqrt(CurrentMoonImpact ** 2 + CurrentHorizontalMoonPosition ** 2) * StellarRadius if CurrentDistanceMoonPlanet < PlanetRadius * StellarRadius: OccultedDataPoints.append(i) if len(OccultedDataPoints) > 0: FirstOcculted = OccultedDataPoints[0] LastOcculted = OccultedDataPoints[-1] + 1 plt.plot(-coordinates[:FirstOcculted,0], coordinates[:FirstOcculted,1] + PlanetImpact, 'k', zorder = 5) plt.plot(-coordinates[LastOcculted:,0], coordinates[LastOcculted:,1] + PlanetImpact, 'k', zorder = 5) else: plt.plot(-coordinates[::,0], coordinates[::,1] + PlanetImpact, 'k', zorder = 5) # Planet PlanetCircle = plt.Circle((0, PlanetImpact), PlanetRadius, color = 'k', zorder = 4) plt.gcf().gca().add_artist(PlanetCircle) # Moon PosPhase = PhaseToHighlight / float(NumerOfSamples) coordinates[1,::] = Ellipse.xyzPos(time[PosPhase]) if PhaseToHighlight < 0.5: CurrentOrder = 2 # behind the planet else: CurrentOrder = 4 # in front of the planet MoonCircle = plt.Circle((-coordinates[1,0], coordinates[1,1] + PlanetImpact), MoonRadius, color = 'k', zorder = CurrentOrder) plt.gcf().gca().add_artist(MoonCircle) # Square not functional? plt.axis([-1.1, +1.1, -1.1, +1.1], set_aspect='equal', fontsize=16) return plt def riverwithoutnoise( StellarRadius, limb1, limb2, PlanetRadius, PlanetAxis, PlanetImpact, PlanetPeriod, MoonRadius, MoonAxis, MoonEccentricity, MoonAscendingNode, MoonLongitudePeriastron, MoonInclination, ShowPlanetMoonEclipses, Quality, NumberOfSamples): """Core function projecting Kepler Moon Ellipse onto PixelGrid""" # Moon's orbit: Kepler ellipse normalized to 1x1 stellar radii NormalizedMoonAxis = MoonAxis / StellarRadius NormalizedMoonRadius = MoonRadius / StellarRadius CounterFullEclipses = 0 CounterPartialEclipses = 0 CurrentEclipsedRatio = 0 Ellipse = pyasl.KeplerEllipse( NormalizedMoonAxis, NormalizedMoonAxis, e = MoonEccentricity, Omega = MoonAscendingNode, w = MoonLongitudePeriastron, i = MoonInclination) time = np.linspace(0., NormalizedMoonAxis, NumberOfSamples) coordinates = np.zeros((len(time), 3), dtype=np.float) for i in xrange(len(time)): coordinates[i,::] = Ellipse.xyzPos(time[i]) StretchSpace = 5 # 5 Grid size [multiples of planet transit duration] UnStretchedTransitDuration = PlanetPeriod / pi * arcsin(sqrt( (MoonRadius + StellarRadius) ** 2) / PlanetAxis) cache = np.zeros((NumberOfSamples, Quality), dtype=np.float) output = np.zeros((NumberOfSamples, StretchSpace * Quality), dtype=np.float) ma = forTrans.MandelAgolLC() # Prepare light curves ma["T0"] = 0 ma["b"] = 0. ma["linLimb"] = limb1 ma["quadLimb"] = limb2 ma["per"] = PlanetPeriod ma["a"] = PlanetAxis / StellarRadius ma["p"] = MoonRadius / StellarRadius time = np.linspace(ma["per"] - (0.5 * UnStretchedTransitDuration), ma["per"] + (0.5 * UnStretchedTransitDuration), Quality) for i in range(NumberOfSamples): # Fetch curves: The core of this function CurrentMoonImpact = coordinates[i, 1] # Position-dependent moon impact CurrentHorizontalMoonPosition = coordinates[i, 0] ma["i"] = ImpactToInclination( CurrentMoonImpact + PlanetImpact, StellarRadius, PlanetAxis) cache[i,::] = ma.evaluate(time) # Fetch each curve # Mutual eclipses: calculate distance moon --> planet [km] if ShowPlanetMoonEclipses: CurrentDistanceMoonPlanet = sqrt(CurrentMoonImpact ** 2 + CurrentHorizontalMoonPosition ** 2) * StellarRadius CurrentEclipsedRatio = EclipsedRatio( CurrentDistanceMoonPlanet, PlanetRadius, MoonRadius) for k in range(Quality): # Transform flux from e.g. 0.995 to -5ppm cache[i, k] = -(1 - cache[i, k]) * 10 ** 6 # And reduce the flux according to the eclipsed area if ShowPlanetMoonEclipses and cache[i, k] < 0: cache[i, k] = -(1 - cache[i, k]) * (1 - CurrentEclipsedRatio) for i in range(NumberOfSamples): # Apply time shift due to moon orbit for k in range(Quality): HorizontalPixelPosition = (coordinates[i, 0] * Quality) / 2 MidShift = (0.5 * StretchSpace - 0.5) * Quality output[i, k + HorizontalPixelPosition + MidShift] = cache[i, k] return output def river( StellarRadius, limb1, limb2, PlanetRadius, PlanetAxis, PlanetImpact, PlanetPeriod, MoonRadius, MoonAxis, MoonEccentricity, MoonAscendingNode, MoonLongitudePeriastron, MoonInclination, ShowPlanetMoonEclipses, Quality, NumberOfSamples, Noise): """Draw the river plot. Get map from RiverWithoutNoise.""" StretchSpace = 5 # 5 times longer than a transit duration map = riverwithoutnoise( # Get noiseless map StellarRadius, limb1, limb2, PlanetRadius, PlanetAxis, PlanetImpact, PlanetPeriod, MoonRadius, MoonAxis, MoonEccentricity, MoonAscendingNode, MoonLongitudePeriastron, MoonInclination, ShowPlanetMoonEclipses, Quality, NumberOfSamples) # Calculate helper variables for noise level per pixel PlanetTransitDuration = PlanetPeriod / pi * arcsin(sqrt( (2 * StellarRadius + 2 * PlanetRadius) ** 2) / PlanetAxis) Pixeltimestep = PlanetTransitDuration / float(Quality) timeResolution = Pixeltimestep * 24 * 60 # Prepare the amount of noise per pixel (=integration) # NoisePerIntegration [ppm/integration] = Noise [ppm/minute] # / sqrt(Integrationtime / 1 [Minute]) NoisePerIntegration = Noise / sqrt(timeResolution) for i in range(NumberOfSamples): # Now spread the noise for k in range(StretchSpace * Quality): # Check if noise is desired. if Noise <= 0: # Skip the (computationally expensive) noise calc RandomNumber = 0 else: # Gaussian noise of mean=0; stdev=NoisePerIntegration # Can be swapped for any other noise law, or even real data RandomNumber = np.random.normal(0, NoisePerIntegration, 1) map[i, k] = map[i, k] + RandomNumber # Add the noise to the map return map def timeaxis(PlanetPeriod, PlanetAxis, MoonRadius, StellarRadius, Quality): Duration = PlanetPeriod / pi * arcsin(sqrt( (StellarRadius + MoonRadius) ** 2) / PlanetAxis) StretchSpace = 5 * Quality time = np.linspace(-2.5 * Duration, 2.5 * Duration, StretchSpace) return time def curve( StellarRadius, limb1, limb2, PlanetRadius, PlanetAxis, PlanetImpact, PlanetPeriod, MoonRadius, MoonAxis, MoonEccentricity, MoonAscendingNode, MoonLongitudePeriastron, MoonInclination, PlanetMoonEclipses, ShowPlanet, Quality, NumberOfSamples, Noise, NumberOfTransits): """Calculate the curve. Use map as source.""" HorizontalResolution = 5 * Quality curve = np.zeros((2, HorizontalResolution), dtype=np.float) curve[0,::] = timeaxis( PlanetPeriod, PlanetAxis, MoonRadius, StellarRadius, Quality) # Get the MapMoon with noise; if noise=0 then none will be added MapMoon = river( StellarRadius, limb1, limb2, PlanetRadius, PlanetAxis, PlanetImpact, PlanetPeriod, MoonRadius, MoonAxis, MoonEccentricity, MoonAscendingNode, MoonLongitudePeriastron, MoonInclination, PlanetMoonEclipses, Quality, NumberOfSamples, Noise) if ShowPlanet: # If wanted: Add noiseless planet curve MapPlanet = river(StellarRadius, limb1, limb2, PlanetRadius, PlanetAxis, PlanetImpact, PlanetPeriod, PlanetRadius, 1., 0., 0., 0., 90., False, Quality, 1, 0) if NumberOfTransits == 0: # Full OSE curve is requested for i in range(HorizontalResolution): Collector = 0 for k in range(NumberOfSamples): Collector = Collector + MapMoon[k,i] Chartflux = Collector / (NumberOfSamples) curve[1, i] = Chartflux else: # Get a subset MapMoonObserved = np.zeros((NumberOfTransits, HorizontalResolution), dtype=np.float) # Fetch #NumberOfTransits transits and push them to #MapMoonObserved for k in range(NumberOfTransits): # Instead of the random selection, one might introduce a rule to # select orbits according to phase time, e.g. observing the transit # at phase=0.17 at first visit, then 0.34, then 0.51... MyRandomTransit = np.random.uniform(0, NumberOfSamples) # <== apply other rule here for i in range(HorizontalResolution - 1): MapMoonObserved[k, i] = MapMoonObserved[k, i] + \ MapMoon[MyRandomTransit, i] # Collector routine now using subset:MapMoonObserved; compensate for flux for i in range(HorizontalResolution): Collector = 0 for k in range(NumberOfTransits): Collector = Collector + MapMoonObserved[k, i] Chartflux = Collector / float(NumberOfSamples) curve[1, i] = Chartflux * (NumberOfSamples / float(NumberOfTransits)) if ShowPlanet: curve[1, ::] = curve[1, ::] + MapPlanet[0, ::] return curve def integral( StellarRadius, limb1, limb2, PlanetRadius, PlanetAxis, PlanetImpact, PlanetPeriod, MoonRadius, MoonAxis, MoonEccentricity, MoonAscendingNode, MoonLongitudePeriastron, MoonInclination, PlanetMoonEclipses, ShowPlanet, Quality, NumberOfSamples, Noise, NumberOfTransits): """Calculate the integral. Use curve as source.""" MyCurve = curve( StellarRadius, limb1, limb2, PlanetRadius, PlanetAxis, PlanetImpact, PlanetPeriod, MoonRadius, MoonAxis, MoonEccentricity, MoonAscendingNode, MoonLongitudePeriastron, MoonInclination, PlanetMoonEclipses, ShowPlanet, Quality, NumberOfSamples, Noise, NumberOfTransits) time = MyCurve[0][::] flux = MyCurve[1][::] TimeLength = time[0] TimeStep = time[1] - time[0] NumberOfBins = TimeLength / TimeStep TotalFlux = np.sum(flux) return TotalFlux * TimeLength / NumberOfBins * 24 # [ppm hrs] def CircleCircleIntersect(radius1, radius2, distance): """Calculates area of asymmetric "lens" in which two circles intersect Source: http://mathworld.wolfram.com/Circle-CircleIntersection.html""" return radius1 ** 2 * (arccos(((distance ** 2) + (radius1 ** 2) - (radius2 ** 2)) / (2 * distance * radius1))) + ((radius2 ** 2) * (arccos((((distance ** 2) + (radius2 ** 2) - (radius1 ** 2)) / (2 * distance * radius2))))) - (0.5 * sqrt((-distance + radius1 + radius2) * (distance + radius1 - radius2) * (distance - radius1 + radius2) * (distance + radius1 + radius2))) def EclipsedRatio(CurrentDistanceMoonPlanet, PlanetRadius, MoonRadius): """Returns eclipsed ratio [0..1] using CircleCircleIntersect""" HasFullEclipse = False HasMutualEclipse = False CurrentEclipsedRatio = 0 if abs(CurrentDistanceMoonPlanet) < (PlanetRadius + MoonRadius): HasMutualEclipse = True if ((PlanetRadius - MoonRadius) > abs(CurrentDistanceMoonPlanet)): HasFullEclipse = True # For partial eclipses, get the fraction of moon eclipse using transit if HasMutualEclipse and not HasFullEclipse: CurrentEclipsedRatio = CircleCircleIntersect( PlanetRadius, MoonRadius, CurrentDistanceMoonPlanet) # ...and transform this value into how much AREA is really eclipsed CurrentEclipsedRatio = CurrentEclipsedRatio / (pi * MoonRadius ** 2) if HasFullEclipse: CurrentEclipsedRatio = 1.0 return CurrentEclipsedRatio def ImpactToInclination(PlanetImpact, StellarRadius, PlanetAxis): """Converts planet impact parameter b = [0..1.x] to inclination [deg]""" return degrees(arccos(PlanetImpact * StellarRadius / PlanetAxis)) def QuadraticLimbDarkening(Impact, limb1, limb2): """Quadratic limb darkening. Kopal 1950, Harvard Col. Obs. Circ., 454, 1""" return 1 - limb1 * (1 - Impact) - limb2 * (1 - Impact) ** 2
{ "repo_name": "hippke/PyOSE", "path": "PyOSE.py", "copies": "1", "size": "15868", "license": "mit", "hash": 9089201926173079000, "line_mean": 43.0777777778, "line_max": 88, "alpha_frac": 0.6458280817, "autogenerated": false, "ratio": 3.355466271939099, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4501294353639099, "avg_score": null, "num_lines": null }
# 200 = a * 100 + b * 50 + c * 20 + d * 10 + e * 5 + f * 2 + g def count(money, level): if level == 1: return 1 elif level == 2: possible = money // 2 sum = 0 for i in range(0, possible + 1): sum += count(money - i * 2, 1) return sum elif level == 5: possible = money // 5 sum = 0 for i in range(0, possible + 1): sum += count(money - i * 5, 2) return sum elif level == 10: possible = money // 10 sum = 0 for i in range(0, possible + 1): sum += count(money - i * 10, 5) return sum elif level == 20: possible = money // 20 sum = 0 for i in range(0, possible + 1): sum += count(money - i * 20, 10) return sum elif level == 50: possible = money // 50 sum = 0 for i in range(0, possible + 1): sum += count(money - i * 50, 20) return sum elif level == 100: possible = money // 100 sum = 0 for i in range(0, possible + 1): sum += count(money - i * 100, 50) return sum elif level == 200: possible = money // 200 sum = 0 for i in range(0, possible + 1): sum += count(money - i * 200, 100) return sum print(count(200, 200))
{ "repo_name": "xnap/projecteuler", "path": "31.py", "copies": "1", "size": "1366", "license": "mit", "hash": 4382195763776500700, "line_mean": 26.32, "line_max": 62, "alpha_frac": 0.4494875549, "autogenerated": false, "ratio": 3.672043010752688, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9517182739565732, "avg_score": 0.020869565217391303, "num_lines": 50 }
"""200. Number of Islands https://leetcode.com/problems/number-of-islands/ Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: 11110 11010 11000 00000 Output: 1 Example 2: Input: 11000 11000 00100 00011 Output: 3 """ from typing import List class Solution: def num_islands(self, grid: List[List[str]]) -> int: if not grid or not grid[0]: return 0 rows, cols = len(grid), len(grid[0]) def dfs(row: int, col: int): if row < 0 or row >= rows or col < 0 or col >= cols: return if grid[row][col] == '0': return grid[row][col] = '0' dfs(row - 1, col) dfs(row + 1, col) dfs(row, col - 1) dfs(row, col + 1) count = 0 for i in range(rows): for j in range(cols): if grid[i][j] == '1': dfs(i, j) count += 1 return count
{ "repo_name": "isudox/leetcode-solution", "path": "python-algorithm/leetcode/number_of_islands.py", "copies": "1", "size": "1193", "license": "mit", "hash": -444083736101085600, "line_mean": 19.9298245614, "line_max": 78, "alpha_frac": 0.5398155909, "autogenerated": false, "ratio": 3.3796033994334276, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9419418990333428, "avg_score": 0, "num_lines": 57 }
# 200. Number of Islands # # Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. # An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. # You may assume all four edges of the grid are all surrounded by water. # # Example 1: # # 11110 # 11010 # 11000 # 00000 # Answer: 1 # # Example 2: # # 11000 # 11000 # 00100 # 00011 # Answer: 3 class Solution(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int http://www.tangjikai.com/algorithms/leetcode-200-number-of-islands We use a visited array to track whether the element is visited or not. When we find a unvisited '1', DFS to mark all surrounding '1' to visited, then find other '1's. Complexity: O(mn) time O(mn) space """ m = len(grid) if m == 0: return 0 n = len(grid[0]) visited = [[False] * n for _ in range(m)] res = 0 for i in range(m): for j in range(n): if grid[i][j] == '1' and not visited[i][j]: self.dfs(i, j, grid, visited) res += 1 return res def dfs(self, i, j, grid, visited): visited[i][j] = True if i + 1 < len(grid) and grid[i + 1][j] == '1' and not visited[i + 1][j]: self.dfs(i + 1, j, grid, visited) if j + 1 < len(grid[0]) and grid[i][j + 1] == '1' and not visited[i][j + 1]: self.dfs(i, j + 1, grid, visited) if i - 1 >= 0 and grid[i - 1][j] == '1' and not visited[i - 1][j]: self.dfs(i - 1, j, grid, visited) if j - 1 >= 0 and grid[i][j - 1] == '1' and not visited[i][j - 1]: self.dfs(i, j - 1, grid, visited) class Solution(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int http://zxi.mytechroad.com/blog/searching/leetcode-200-number-of-islands/ for every land (1), visit its neighbor land using DFS, until there is no land, mark visited node as 0 (water). """ m = len(grid) if m == 0: return 0 n = len(grid[0]) ans = 0 for i in range(m): for j in range(n): if grid[i][j] == '1': ans += 1 self.dfs(grid, i, j, m, n) return ans def dfs(self, grid, i, j, m, n): if i < 0 or j < 0 or i >= m or j >= n or grid[i][j] == '0': return grid[i][j] = '0' self.dfs(grid, i + 1, j, m, n) self.dfs(grid, i - 1, j, m, n) self.dfs(grid, i, j + 1, m, n) self.dfs(grid, i, j - 1, m, n) # same as above solution, but put dfs func inside # this way no need for m, n def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ def dfs(grid, i, j): # reaches border or water if i < 0 or j < 0 or i >= m or j >= n or grid[i][j] == '0': return grid[i][j] = '0' dfs(grid, i, j + 1) dfs(grid, i, j - 1) dfs(grid, i - 1, j) dfs(grid, i + 1, j) m = len(grid) if m == 0: return 0 n = len(grid[0]) res = 0 for i in range(m): for j in range(n): if grid[i][j] == '1': dfs(grid, i, j) res += 1 return res
{ "repo_name": "gengwg/leetcode", "path": "200_number_of_islands.py", "copies": "1", "size": "3569", "license": "apache-2.0", "hash": -1805888363420235500, "line_mean": 26.6744186047, "line_max": 105, "alpha_frac": 0.4704398991, "autogenerated": false, "ratio": 3.1923076923076925, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4162747591407693, "avg_score": null, "num_lines": null }
# 2010-07-17 - 2011-01-16 @ david barkhuizen # yahoo finance harvester component import http.client http.client.HTTPConnection.debuglevel = 0 import urllib URL_STEM = 'http://ichart.finance.yahoo.com/table.csv?' def construct_ichart_csv_url(symbol, fromY, fromM, fromD, toY, toM, toD): ''' ('BP', '1900', '01', '01', '2010', '07', '18') ''' q = dict() q['s'] = symbol q['a'] = str(int(fromM) - 1) q['b'] = fromD q['c'] = fromY q['d'] = str(int(toM) - 1) q['e'] = toD q['f'] = toY q['g'] = 'd' # valid example as @ 2011/01/16 # http://ichart.finance.yahoo.com/table.csv? s=JPM &a=11 &b=30 &c=1983 &d=00 &e=16 &f=2011 &g=d &ignore=.csv # 1983-12-30 -> 2011-01-16 # http://ichart.finance.yahoo.com/table.csv?s=JPM &a=05 &b=1 &c=1983 &d=06 &e=1 &f=2011 &g=d &ignore=.csv # 1983-06-01 -> 2011-07-01 encoded = urllib.urlencode(q) url = URL_STEM + encoded # + "&ignore=.csv" print(url) return url def get_body(url): f = urllib.urlopen(url) body = f.read() f.close() return body def get_csv_lines_for_period(symbol, fromY, fromM, fromD, toY, toM, toD): url = construct_ichart_csv_url(symbol, fromY, fromM, fromD, toY, toM, toD) body = get_body(url) return body
{ "repo_name": "davidbarkhuizen/yfh", "path": "v1/httpadaptor.py", "copies": "1", "size": "1238", "license": "mit", "hash": -7837285653623167000, "line_mean": 21.9259259259, "line_max": 110, "alpha_frac": 0.6025848142, "autogenerated": false, "ratio": 2.41796875, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8057275333121692, "avg_score": 0.09265564621566184, "num_lines": 54 }
""" 2012.06.15 1. This script joins separate Skia .gyp files (core,opts,effects,ports,utils...) into one "gyp/skia_dll_msvs2010e.gyp", that could be used to create one shared lib (dll). see "skia_dll_config" below for more details. 2. Creates "gyp/win32_app.gyp" and "skia_win32.gyp" files. 3. Generates Visual Studio 2010 Express project files. More useful info (to build Release version) could be found in chromium gyp files like: http://src.chromium.org/viewvc/chrome/trunk/src/build/common.gypi """ import os import sys import pprint script_dir = os.path.dirname(__file__) # Directory within which we can find the gyp source. gyp_source_dir = os.path.join(script_dir, 'third_party', 'externals', 'gyp') # Directory within which we can find most of Skia's gyp configuration files. gyp_config_dir = os.path.join(script_dir, 'gyp') # Directory within which we want all generated files (including Makefiles) # to be written. output_dir = os.path.join(os.path.abspath(script_dir), 'out') sys.path.append(os.path.join(gyp_source_dir, 'pylib')) import gyp skia_win32_config = """ { 'targets': [ { # Use this target to build everything provided by Skia. 'target_name': 'main', 'type': 'none', 'dependencies': [ 'gyp/win32_app.gyp:win32_app', # this will include skia_dll.gyp ], }, ], } """ win32_app_config = """ { 'targets': [{ 'target_name': 'win32_app', 'type': 'executable', 'defines': [ 'SKIA_DLL', 'WIN32', #'SKIA_IMPLEMENTATION=1', commented - so it will be using dllimport (instead of export) #'SK_RELEASE' # define this in SkUserConfig.h '_UNICODE', 'UNICODE', 'OS_WIN', # for /ext ], 'sources': [ '../win32_app/skia_app.cpp', ], 'dependencies' : [ 'skia_dll_msvs2010e.gyp:skia', ], 'include_dirs' : [ '../', '../include/config/', '../include/effects/', '../include/core/', ], 'link_settings': { 'libraries': [ '-lskia.lib', ], }, 'msvs_settings': { 'VCLinkerTool': { 'AdditionalLibraryDirectories': ['$(OutDir)'], # this must be modified in case it's not Debug }, }, },] } """ skia_dll_config = """ { 'targets' : [ { 'target_name' : 'skia', 'type' : 'shared_library', 'defines': [ 'SKIA_DLL', 'WIN32', 'SKIA_IMPLEMENTATION=1', #'SK_RELEASE' # define this in SkUserConfig.h '_UNICODE', 'UNICODE', 'OS_WIN', # for /ext ], #include\core\skrefcnt.h(28): warning C4251: 'SkRefCnt::fInstanceCountHelper' : class 'SkRefCnt::SkInstanceCountHelper' needs to have dll-interface to be used by clients of class 'SkRefCnt' #include\core\skrefcnt.h(28) : see declaration of 'SkRefCnt::SkInstanceCountHelper' 'msvs_disabled_warnings': [4251], 'link_settings': { 'libraries': [ '-lPsapi.lib' # for /ext ], }, # better shared_library settings: # http://src.chromium.org/svn/trunk/src/build/common.gypi 'msvs_settings': { 'VCCLCompilerTool': { 'ExceptionHandling': '1', # /EHsc 'AdditionalOptions': [ '/EHsc' ], # common_conditions.gypi overwrites 'ExceptionHandling': '0', so we must add /EHsc }, }, 'dependencies' : [ 'core.gyp:core', 'ports.gyp:ports', 'utils.gyp:utils', 'effects.gyp:effects', 'pdf.gyp:pdf', # jo prireike /ext # Note: A more slimmed-down library (with no source edits) can be compiled # by removing all dependencies below this comment, and uncommenting the # SkOSFile.cpp source below. #'animator.gyp:animator', #'gpu.gyp:skgr', #'gpu.gyp:gr', #'xml.gyp:xml', #'opts.gyp:opts', #'svg.gyp:svg', #'views.gyp:views', #'images.gyp:images', ], 'include_dirs' : ['../', ], # kad galetume pasiekti /ext /base ir /build 'sources': [ '../include/config/SkUserConfig.h', '../build/build_config.h', '../base/basictypes.h', '../base/compiler_specific.h', '../base/port.h', # skia extensions from: http://src.chromium.org/viewvc/chrome/trunk/src/skia/skia.gyp?view=markup '../ext/bitmap_platform_device.h', #'../ext/bitmap_platform_device_android.cc', #'../ext/bitmap_platform_device_android.h', '../ext/bitmap_platform_device_data.h', #'../ext/bitmap_platform_device_linux.cc', #'../ext/bitmap_platform_device_linux.h', #'../ext/bitmap_platform_device_mac.cc', #'../ext/bitmap_platform_device_mac.h', '../ext/bitmap_platform_device_win.cc', '../ext/bitmap_platform_device_win.h', '../ext/canvas_paint.h', '../ext/canvas_paint_common.h', #'../ext/canvas_paint_gtk.h', #'ext/canvas_paint_mac.h', '../ext/canvas_paint_win.h', # SITAS SVARBUS #'../ext/convolver.cc', #'../ext/convolver.h', #'../ext/google_logging.cc', #'../ext/image_operations.cc', #'../ext/image_operations.h', #'../ext/SkThread_chrome.cc', '../ext/platform_canvas.cc', '../ext/platform_canvas.h', #'../ext/platform_canvas_linux.cc', #'../ext/platform_canvas_mac.cc', #'../ext/platform_canvas_skia.cc', dubliuoja platform_canvas_win todel gauname linking error'a '../ext/platform_canvas_win.cc', '../ext/platform_device.cc', '../ext/platform_device.h', #'../ext/platform_device_linux.cc', #'../ext/platform_device_mac.cc', '../ext/platform_device_win.cc', #'../ext/SkMemory_new_handler.cpp', # dubliuoja SkMemory_malloc.c (bet gali buti kad jis yra tinkamesnis) #'../ext/skia_sandbox_support_win.h', #'../ext/skia_sandbox_support_win.cc', #'../ext/skia_trace_shim.h', #'../ext/skia_utils_mac.mm', #'../ext/skia_utils_mac.h', '../ext/skia_utils_win.cc', '../ext/skia_utils_win.h', '../ext/vector_canvas.cc', '../ext/vector_canvas.h', '../ext/vector_platform_device_emf_win.cc', '../ext/vector_platform_device_emf_win.h', '../ext/vector_platform_device_skia.cc', '../ext/vector_platform_device_skia.h', ], }, ] } """ def join_gyp_data(config_data, target_data): for key, value in target_data.items(): if not key in config_data: config_data[key] = value # new data elif isinstance(value, list): config_data[key].extend(value) # append list data if key != "conditions": # remove duplicates config_data[key] = list(set(config_data[key])) def create_skia_dll_gyp(config_str, skia_gyp_file): config_data = eval(config_str, {'__builtins__': None}, None) config_target = config_data["targets"][0] dependencies = config_target["dependencies"][:] del config_target["dependencies"] # no longer needed - could be replaced by new dependencies for target in dependencies: path, target_name = target.split(":") path = os.path.join(gyp_config_dir, path) gyp_data = eval(open(path).read(), {'__builtins__': None}, None) targets = gyp_data["targets"] for target_data in targets: if target_data["target_name"] == target_name: join_gyp_data(config_target, target_data) break # remove original dependencies config_target["dependencies"] = list(set(config_target.get("dependencies", [])).difference(set(dependencies))) del config_target["msvs_guid"] # remove core.gyp guid file = open(skia_gyp_file, "w") file.write(pprint.pformat(config_data, width=10, indent=4)) file.close() if __name__ == '__main__': args = [] #sys.argv[1:] # Set CWD to the directory containing this script. # This allows us to launch it from other directories, in spite of gyp's # finickyness about the current working directory. # See http://b.corp.google.com/issue?id=5019517 ('Linux make build # (from out dir) no longer runs skia_gyp correctly') os.chdir(os.path.abspath(script_dir)) # create skia_main.gyp skia_win32_file = "skia_win32.gyp" file = open(skia_win32_file, "w") file.write(skia_win32_config) file.close() # create win32_app.gyp file = open(os.path.join(gyp_config_dir, "win32_app.gyp"), "w") file.write(win32_app_config) file.close() skia_gyp_file = os.path.join(gyp_config_dir, "skia_dll_msvs2010e.gyp") #variables = create_variables("msvs") # galima bus pratestuoti tik su {} #print "variables: ", variables include_file = os.path.join(gyp_config_dir, 'common.gypi') depth = '.' # create skia dll gyp create_skia_dll_gyp(skia_dll_config, skia_gyp_file) args.append(skia_win32_file) # Always include common.gypi. # We do this, rather than including common.gypi explicitly in all our gyp # files, so that gyp files we use but do not maintain (e.g., # third_party/externals/libjpeg/libjpeg.gyp) will include common.gypi too. args.append('-I' + include_file) args.extend(['--depth', depth]) # Tell gyp to write the Makefiles into output_dir args.extend(['--generator-output', os.path.abspath(output_dir)]) # Tell make to write its output into the same dir args.extend(['-Goutput_dir=.']) # Special arguments for generating Visual Studio projects: # - msvs_version forces generation of Visual Studio 2010 project so that we # can use msbuild.exe # - msvs_abspath_output is a workaround for # http://code.google.com/p/gyp/issues/detail?id=201 args.extend(['-Gmsvs_version=2010e']) print 'Updating projects from gyp files...' sys.stdout.flush() # Off we go... print "ARGS: ", args sys.exit(gyp.main(args))
{ "repo_name": "vosvos/skia-win32-dll", "path": "skia_dll_msvs2010e.py", "copies": "1", "size": "11233", "license": "bsd-3-clause", "hash": 3872887527055753000, "line_mean": 32.2469512195, "line_max": 197, "alpha_frac": 0.5312027063, "autogenerated": false, "ratio": 3.728177895784932, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4759380602084932, "avg_score": null, "num_lines": null }
# 2012-2-12 Fix bug where quality was not taking precedence over order # See http://code.google.com/p/mimeparse/issues/detail?id=10 # 2012-2-12 Fix bug where a quality value of 0 was being overwritten with 1 # See http://code.google.com/p/mimeparse/issues/detail?id=15 """MIME-Type Parser This module provides basic functions for handling mime-types. It can handle matching mime-types against a list of media-ranges. See section 14.1 of the HTTP specification [RFC 2616] for a complete explanation. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 Contents: - parse_mime_type(): Parses a mime-type into its component parts. - parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q' quality parameter. - quality(): Determines the quality ('q') of a mime-type when compared against a list of media-ranges. - quality_parsed(): Just like quality() except the second parameter must be pre-parsed. - best_match(): Choose the mime-type with the highest quality ('q') from a list of candidates. """ from functools import reduce __version__ = "0.1.3" __author__ = 'Joe Gregorio' __email__ = "joe@bitworking.org" __credits__ = "" def parse_mime_type(mime_type): """Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', {'q', '0.5'}) """ parts = mime_type.split(";") params = dict([tuple([s.strip() for s in param.split("=")])\ for param in parts[1:] ]) full_type = parts[0].strip() # Java URLConnection class sends an Accept header that includes a single "*" # Turn it into a legal wildcard. if full_type == '*': full_type = '*/*' (type, subtype) = full_type.split("/") return (type.strip(), subtype.strip(), params) def parse_media_range(range): """Carves up a media range and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/*;q=0.5' would get parsed into: ('application', '*', {'q', '0.5'}) In addition this function also guarantees that there is a value for 'q' in the params dictionary, filling it in with a proper default if necessary. """ (type, subtype, params) = parse_mime_type(range) if 'q' not in params or not params['q'] or \ float(params['q']) > 1 or float(params['q']) < 0: params['q'] = '1' return (type, subtype, params) def fitness_and_quality_parsed(mime_type, parsed_ranges): """Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns a tuple of the fitness value and the value of the 'q' quality parameter of the best match, or (-1, 0) if no match was found. Just as for quality_parsed(), 'parsed_ranges' must be a list of parsed media ranges. """ best_fitness = -1 best_fit_q = 0 (target_type, target_subtype, target_params) =\ parse_media_range(mime_type) for (type, subtype, params) in parsed_ranges: if (type == target_type or type == '*' or target_type == '*') and \ (subtype == target_subtype or subtype == '*' or target_subtype == '*'): param_matches = reduce(lambda x, y: x+y, [1 for (key, value) in \ list(target_params.items()) if key != 'q' and \ key in params and value == params[key]], 0) fitness = (type == target_type) and 100 or 0 fitness += (subtype == target_subtype) and 10 or 0 fitness += param_matches if fitness > best_fitness: best_fitness = fitness best_fit_q = params['q'] return float(best_fit_q), best_fitness def quality_parsed(mime_type, parsed_ranges): """Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns the 'q' quality parameter of the best match, 0 if no match was found. This function bahaves the same as quality() except that 'parsed_ranges' must be a list of parsed media ranges. """ return fitness_and_quality_parsed(mime_type, parsed_ranges)[0] def quality(mime_type, ranges): """Returns the quality 'q' of a mime-type when compared against the media-ranges in ranges. For example: >>> quality('text/html','text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5') 0.7 """ parsed_ranges = [parse_media_range(r) for r in ranges.split(",")] return quality_parsed(mime_type, parsed_ranges) def best_match(supported, header): """Takes a list of supported mime-types and finds the best match for all the media-ranges listed in header. The value of header must be a string that conforms to the format of the HTTP Accept: header. The value of 'supported' is a list of mime-types. The list of supported mime-types should be sorted in order of increasing desirability, in case of a situation where there is a tie >>> best_match(['application/xbel+xml', 'text/xml'], 'text/*;q=0.5,*/*; q=0.1') 'text/xml' """ parsed_header = [parse_media_range(r) for r in _filter_blank(header.split(","))] weighted_matches = [] pos = 0 for mime_type in supported: weighted_matches.append((fitness_and_quality_parsed(mime_type, parsed_header), pos, mime_type)) pos += 1 weighted_matches.sort() return weighted_matches[-1][0][0] and weighted_matches[-1][2] or '' def _filter_blank(i): for s in i: if s.strip(): yield s
{ "repo_name": "bruth/restlib2", "path": "restlib2/mimeparse.py", "copies": "1", "size": "5992", "license": "bsd-2-clause", "hash": 6903788586532053000, "line_mean": 42.1079136691, "line_max": 116, "alpha_frac": 0.6320093458, "autogenerated": false, "ratio": 3.6693202694427436, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4801329615242743, "avg_score": null, "num_lines": null }
#2013.06.06 V2 #C:\\Python27\python C:\\Users\Bing\Videos\read2.py #cd C:\\Users\Bing\Videos import os #Set directory old_dir = os.getcwd() #os.chdir('/home/bing/Documents') os.chdir('C:\\Users\Bing\Videos') #Read data from input file and place in table f = open('test.txt', 'r') f.readline() #reads and ignores the first line doc = f.read() table = [s.strip().split('\t') for s in doc.splitlines()] ''' #Error check print '\nError Check 1' print 'The table is' print table ''' #Find table size rows = len(table) print 'There are %r sample reads' % rows #rows should = 15 cols = len(table[0]) print 'There are %r categories' % cols #cols should = 69 ''' #Error Check print '\nError Check 2' print 'Column 14 is' for x in range(0,rows): print table[x][15] ''' #Write data in new file output = open('output.txt', 'w') output.truncate() for x in range(0, rows): for y in range(0, cols): #print table[x][y] #debug output.write('%r\t' % table[x][y]) output.write('\n') output.close() #Make table of only KEEP #print '\nTest Table Search' table_keeps = [] for x in range (0, rows): #print '\n table_keeps1 is %r' % table_keeps if table[x][68] == 'KEEP': #look only at column 69, which is KEEP or REJECT table_keeps.append(table[x]) keeps_rows = len(table_keeps) print 'There are %r rows with cited mutations' % keeps_rows output = open('output_keeps.txt', 'w') output.truncate() for x in range(0, keeps_rows): for y in range(0, cols): #print table[x][y] #debug output.write('%r\t' % table_keeps[x][y]) output.write('\n') output.close() os.chdir(old_dir)
{ "repo_name": "kotoroshinoto/Cluster_SimpleJob_Generator", "path": "pybin/MutectAnalysis/Drafts/methodslistDraft2.py", "copies": "1", "size": "1581", "license": "unlicense", "hash": 8929349348155658000, "line_mean": 22.6119402985, "line_max": 76, "alpha_frac": 0.6654016445, "autogenerated": false, "ratio": 2.657142857142857, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.38225445016428566, "avg_score": null, "num_lines": null }
# 2013.08.22 22:25:33 Pacific Daylight Time # Embedded file name: toontown.suit.Suit from direct.actor import Actor from otp.avatar import Avatar import SuitDNA from toontown.toonbase import ToontownGlobals from pandac.PandaModules import * from toontown.battle import SuitBattleGlobals from direct.task.Task import Task from toontown.battle import BattleProps from toontown.toonbase import TTLocalizer from pandac.PandaModules import VirtualFileMountHTTP, VirtualFileSystem, Filename, DSearchPath from direct.showbase import AppRunnerGlobal from otp.nametag import NametagGroup import string import os aSize = 6.06 bSize = 5.29 cSize = 4.14 SuitDialogArray = [] SkelSuitDialogArray = [] AllSuits = (('walk', 'walk'), ('run', 'walk'), ('neutral', 'neutral')) AllSuitsMinigame = (('victory', 'victory'), ('flail', 'flailing'), ('tug-o-war', 'tug-o-war'), ('slip-backward', 'slip-backward'), ('slip-forward', 'slip-forward')) AllSuitsTutorialBattle = (('lose', 'lose'), ('pie-small-react', 'pie-small'), ('squirt-small-react', 'squirt-small')) AllSuitsBattle = (('drop-react', 'anvil-drop'), ('flatten', 'drop'), ('sidestep-left', 'sidestep-left'), ('sidestep-right', 'sidestep-right'), ('squirt-large-react', 'squirt-large'), ('landing', 'landing'), ('reach', 'walknreach'), ('rake-react', 'rake'), ('hypnotized', 'hypnotize'), ('soak', 'soak')) SuitsCEOBattle = (('sit', 'sit'), ('sit-eat-in', 'sit-eat-in'), ('sit-eat-loop', 'sit-eat-loop'), ('sit-eat-out', 'sit-eat-out'), ('sit-angry', 'sit-angry'), ('sit-hungry-left', 'leftsit-hungry'), ('sit-hungry-right', 'rightsit-hungry'), ('sit-lose', 'sit-lose'), ('tray-walk', 'tray-walk'), ('tray-neutral', 'tray-neutral'), ('sit-lose', 'sit-lose')) f = (('throw-paper', 'throw-paper', 3.5), ('phone', 'phone', 3.5), ('shredder', 'shredder', 3.5)) p = (('pencil-sharpener', 'pencil-sharpener', 5), ('pen-squirt', 'pen-squirt', 5), ('hold-eraser', 'hold-eraser', 5), ('finger-wag', 'finger-wag', 5), ('hold-pencil', 'hold-pencil', 5)) ym = (('throw-paper', 'throw-paper', 5), ('golf-club-swing', 'golf-club-swing', 5), ('magic3', 'magic3', 5), ('rubber-stamp', 'rubber-stamp', 5), ('smile', 'smile', 5)) mm = (('speak', 'speak', 5), ('effort', 'effort', 5), ('magic1', 'magic1', 5), ('pen-squirt', 'fountain-pen', 5), ('finger-wag', 'finger-wag', 5)) ds = (('magic1', 'magic1', 5), ('magic2', 'magic2', 5), ('throw-paper', 'throw-paper', 5), ('magic3', 'magic3', 5)) hh = (('pen-squirt', 'fountain-pen', 7), ('glower', 'glower', 5), ('throw-paper', 'throw-paper', 5), ('magic1', 'magic1', 5), ('roll-o-dex', 'roll-o-dex', 5)) cr = (('pickpocket', 'pickpocket', 5), ('throw-paper', 'throw-paper', 3.5), ('glower', 'glower', 5)) tbc = (('cigar-smoke', 'cigar-smoke', 8), ('glower', 'glower', 5), ('song-and-dance', 'song-and-dance', 8), ('golf-club-swing', 'golf-club-swing', 5)) cc = (('speak', 'speak', 5), ('glower', 'glower', 5), ('phone', 'phone', 3.5), ('finger-wag', 'finger-wag', 5)) tm = (('speak', 'speak', 5), ('throw-paper', 'throw-paper', 5), ('pickpocket', 'pickpocket', 5), ('roll-o-dex', 'roll-o-dex', 5), ('finger-wag', 'finger-wag', 5)) nd = (('pickpocket', 'pickpocket', 5), ('roll-o-dex', 'roll-o-dex', 5), ('magic3', 'magic3', 5), ('smile', 'smile', 5)) gh = (('speak', 'speak', 5), ('pen-squirt', 'fountain-pen', 5), ('rubber-stamp', 'rubber-stamp', 5)) ms = (('effort', 'effort', 5), ('throw-paper', 'throw-paper', 5), ('stomp', 'stomp', 5), ('quick-jump', 'jump', 6)) tf = (('phone', 'phone', 5), ('smile', 'smile', 5), ('throw-object', 'throw-object', 5), ('glower', 'glower', 5)) m = (('speak', 'speak', 5), ('magic2', 'magic2', 5), ('magic1', 'magic1', 5), ('golf-club-swing', 'golf-club-swing', 5)) mh = (('magic1', 'magic1', 5), ('smile', 'smile', 5), ('golf-club-swing', 'golf-club-swing', 5), ('song-and-dance', 'song-and-dance', 5)) sc = (('throw-paper', 'throw-paper', 3.5), ('watercooler', 'watercooler', 5), ('pickpocket', 'pickpocket', 5)) pp = (('throw-paper', 'throw-paper', 5), ('glower', 'glower', 5), ('finger-wag', 'fingerwag', 5)) tw = (('throw-paper', 'throw-paper', 3.5), ('glower', 'glower', 5), ('magic2', 'magic2', 5), ('finger-wag', 'finger-wag', 5)) bc = (('phone', 'phone', 5), ('hold-pencil', 'hold-pencil', 5)) nc = (('phone', 'phone', 5), ('throw-object', 'throw-object', 5)) mb = (('magic1', 'magic1', 5), ('throw-paper', 'throw-paper', 3.5)) ls = (('throw-paper', 'throw-paper', 5), ('throw-object', 'throw-object', 5), ('hold-pencil', 'hold-pencil', 5)) rb = (('glower', 'glower', 5), ('magic1', 'magic1', 5), ('golf-club-swing', 'golf-club-swing', 5)) bf = (('pickpocket', 'pickpocket', 5), ('rubber-stamp', 'rubber-stamp', 5), ('shredder', 'shredder', 3.5), ('watercooler', 'watercooler', 5)) b = (('effort', 'effort', 5), ('throw-paper', 'throw-paper', 5), ('throw-object', 'throw-object', 5), ('magic1', 'magic1', 5)) dt = (('rubber-stamp', 'rubber-stamp', 5), ('throw-paper', 'throw-paper', 5), ('speak', 'speak', 5), ('finger-wag', 'fingerwag', 5), ('throw-paper', 'throw-paper', 5)) ac = (('throw-object', 'throw-object', 5), ('roll-o-dex', 'roll-o-dex', 5), ('stomp', 'stomp', 5), ('phone', 'phone', 5), ('throw-paper', 'throw-paper', 5)) bs = (('magic1', 'magic1', 5), ('throw-paper', 'throw-paper', 5), ('finger-wag', 'fingerwag', 5)) sd = (('magic2', 'magic2', 5), ('quick-jump', 'jump', 6), ('stomp', 'stomp', 5), ('magic3', 'magic3', 5), ('hold-pencil', 'hold-pencil', 5), ('throw-paper', 'throw-paper', 5)) le = (('speak', 'speak', 5), ('throw-object', 'throw-object', 5), ('glower', 'glower', 5), ('throw-paper', 'throw-paper', 5)) bw = (('finger-wag', 'fingerwag', 5), ('cigar-smoke', 'cigar-smoke', 8), ('gavel', 'gavel', 8), ('magic1', 'magic1', 5), ('throw-object', 'throw-object', 5), ('throw-paper', 'throw-paper', 5)) if not base.config.GetBool('want-new-cogs', 0): ModelDict = {'a': ('/models/char/suitA-', 4), 'b': ('/models/char/suitB-', 4), 'c': ('/models/char/suitC-', 3.5)} TutorialModelDict = {'a': ('/models/char/suitA-', 4), 'b': ('/models/char/suitB-', 4), 'c': ('/models/char/suitC-', 3.5)} else: ModelDict = {'a': ('/models/char/tt_a_ene_cga_', 4), 'b': ('/models/char/tt_a_ene_cgb_', 4), 'c': ('/models/char/tt_a_ene_cgc_', 3.5)} TutorialModelDict = {'a': ('/models/char/tt_a_ene_cga_', 4), 'b': ('/models/char/tt_a_ene_cgb_', 4), 'c': ('/models/char/tt_a_ene_cgc_', 3.5)} HeadModelDict = {'a': ('/models/char/suitA-', 4), 'b': ('/models/char/suitB-', 4), 'c': ('/models/char/suitC-', 3.5)} def loadTutorialSuit(): loader.loadModelNode('phase_3.5/models/char/suitC-mod') loadDialog(1) def loadSuits(level): loadSuitModelsAndAnims(level, flag=1) loadDialog(level) def unloadSuits(level): loadSuitModelsAndAnims(level, flag=0) unloadDialog(level) def loadSuitModelsAndAnims(level, flag = 0): for key in ModelDict.keys(): model, phase = ModelDict[key] if base.config.GetBool('want-new-cogs', 0): headModel, headPhase = HeadModelDict[key] else: headModel, headPhase = ModelDict[key] if flag: if base.config.GetBool('want-new-cogs', 0): filepath = 'phase_3.5' + model + 'zero' if cogExists(model + 'zero.bam'): loader.loadModelNode(filepath) else: loader.loadModelNode('phase_3.5' + model + 'mod') loader.loadModelNode('phase_' + str(headPhase) + headModel + 'heads') else: if base.config.GetBool('want-new-cogs', 0): filepath = 'phase_3.5' + model + 'zero' if cogExists(model + 'zero.bam'): loader.unloadModel(filepath) else: loader.unloadModel('phase_3.5' + model + 'mod') loader.unloadModel('phase_' + str(headPhase) + headModel + 'heads') def cogExists(filePrefix): searchPath = DSearchPath() if AppRunnerGlobal.appRunner: searchPath.appendDirectory(Filename.expandFrom('$TT_3_5_ROOT/phase_3.5')) else: basePath = os.path.expandvars('$TTMODELS') or './ttmodels' searchPath.appendDirectory(Filename.fromOsSpecific(basePath + '/built/phase_3.5')) filePrefix = filePrefix.strip('/') pfile = Filename(filePrefix) found = vfs.resolveFilename(pfile, searchPath) if not found: return False return True def loadSuitAnims(suit, flag = 1): if suit in SuitDNA.suitHeadTypes: try: animList = eval(suit) except NameError: animList = () else: print 'Invalid suit name: ', suit return -1 for anim in animList: phase = 'phase_' + str(anim[2]) filePrefix = ModelDict[bodyType][0] animName = filePrefix + anim[1] if flag: loader.loadModelNode(animName) else: loader.unloadModel(animName) def loadDialog(level): global SuitDialogArray if len(SuitDialogArray) > 0: return else: loadPath = 'phase_3.5/audio/dial/' SuitDialogFiles = ['COG_VO_grunt', 'COG_VO_murmur', 'COG_VO_statement', 'COG_VO_question'] for file in SuitDialogFiles: SuitDialogArray.append(base.loadSfx(loadPath + file + '.ogg')) SuitDialogArray.append(SuitDialogArray[2]) SuitDialogArray.append(SuitDialogArray[2]) def loadSkelDialog(): global SkelSuitDialogArray if len(SkelSuitDialogArray) > 0: return else: grunt = loader.loadSfx('phase_5/audio/sfx/Skel_COG_VO_grunt.ogg') murmur = loader.loadSfx('phase_5/audio/sfx/Skel_COG_VO_murmur.ogg') statement = loader.loadSfx('phase_5/audio/sfx/Skel_COG_VO_statement.ogg') question = loader.loadSfx('phase_5/audio/sfx/Skel_COG_VO_question.ogg') SkelSuitDialogArray = [grunt, murmur, statement, question, statement, statement] def unloadDialog(level): global SuitDialogArray SuitDialogArray = [] def unloadSkelDialog(): global SkelSuitDialogArray SkelSuitDialogArray = [] def attachSuitHead(node, suitName): suitIndex = SuitDNA.suitHeadTypes.index(suitName) suitDNA = SuitDNA.SuitDNA() suitDNA.newSuit(suitName) suit = Suit() suit.setDNA(suitDNA) headParts = suit.getHeadParts() head = node.attachNewNode('head') for part in headParts: copyPart = part.copyTo(head) copyPart.setDepthTest(1) copyPart.setDepthWrite(1) suit.delete() suit = None p1 = Point3() p2 = Point3() head.calcTightBounds(p1, p2) d = p2 - p1 biggest = max(d[0], d[2]) column = suitIndex % SuitDNA.suitsPerDept s = (0.2 + column / 100.0) / biggest pos = -0.14 + (SuitDNA.suitsPerDept - column - 1) / 135.0 head.setPosHprScale(0, 0, pos, 180, 0, 0, s, s, s) return head class Suit(Avatar.Avatar): __module__ = __name__ healthColors = (Vec4(0, 1, 0, 1), Vec4(1, 1, 0, 1), Vec4(1, 0.5, 0, 1), Vec4(1, 0, 0, 1), Vec4(0.3, 0.3, 0.3, 1)) healthGlowColors = (Vec4(0.25, 1, 0.25, 0.5), Vec4(1, 1, 0.25, 0.5), Vec4(1, 0.5, 0.25, 0.5), Vec4(1, 0.25, 0.25, 0.5), Vec4(0.3, 0.3, 0.3, 0)) medallionColors = {'c': Vec4(0.863, 0.776, 0.769, 1.0), 's': Vec4(0.843, 0.745, 0.745, 1.0), 'l': Vec4(0.749, 0.776, 0.824, 1.0), 'm': Vec4(0.749, 0.769, 0.749, 1.0)} def __init__(self): try: self.Suit_initialized return except: self.Suit_initialized = 1 Avatar.Avatar.__init__(self) self.setFont(ToontownGlobals.getSuitFont()) self.setPlayerType(NametagGroup.CCSuit) self.setPickable(1) self.leftHand = None self.rightHand = None self.shadowJoint = None self.nametagJoint = None self.headParts = [] self.healthBar = None self.healthCondition = 0 self.isDisguised = 0 self.isWaiter = 0 self.isRental = 0 return def delete(self): try: self.Suit_deleted except: self.Suit_deleted = 1 if self.leftHand: self.leftHand.removeNode() self.leftHand = None if self.rightHand: self.rightHand.removeNode() self.rightHand = None if self.shadowJoint: self.shadowJoint.removeNode() self.shadowJoint = None if self.nametagJoint: self.nametagJoint.removeNode() self.nametagJoint = None for part in self.headParts: part.removeNode() self.headParts = [] self.removeHealthBar() Avatar.Avatar.delete(self) return def setHeight(self, height): Avatar.Avatar.setHeight(self, height) self.nametag3d.setPos(0, 0, height + 1.0) def getRadius(self): return 2 def setDNAString(self, dnaString): self.dna = SuitDNA.SuitDNA() self.dna.makeFromNetString(dnaString) self.setDNA(self.dna) def setDNA(self, dna): if self.style: pass else: self.style = dna self.generateSuit() self.initializeDropShadow() self.initializeNametag3d() def generateSuit(self): dna = self.style self.headParts = [] self.headColor = None self.headTexture = None self.loseActor = None self.isSkeleton = 0 if dna.name == 'f': self.scale = 4.0 / cSize self.handColor = SuitDNA.corpPolyColor self.generateBody() self.generateHead('flunky') self.generateHead('glasses') self.setHeight(4.88) elif dna.name == 'p': self.scale = 3.35 / bSize self.handColor = SuitDNA.corpPolyColor self.generateBody() self.generateHead('pencilpusher') self.setHeight(5.0) elif dna.name == 'ym': self.scale = 4.125 / aSize self.handColor = SuitDNA.corpPolyColor self.generateBody() self.generateHead('yesman') self.setHeight(5.28) elif dna.name == 'mm': self.scale = 2.5 / cSize self.handColor = SuitDNA.corpPolyColor self.generateBody() self.generateHead('micromanager') self.setHeight(3.25) elif dna.name == 'ds': self.scale = 4.5 / bSize self.handColor = SuitDNA.corpPolyColor self.generateBody() self.generateHead('beancounter') self.setHeight(6.08) elif dna.name == 'hh': self.scale = 6.5 / aSize self.handColor = SuitDNA.corpPolyColor self.generateBody() self.generateHead('headhunter') self.setHeight(7.45) elif dna.name == 'cr': self.scale = 6.75 / cSize self.handColor = VBase4(0.85, 0.55, 0.55, 1.0) self.generateBody() self.headTexture = 'corporate-raider.jpg' self.generateHead('flunky') self.setHeight(8.23) elif dna.name == 'tbc': self.scale = 7.0 / aSize self.handColor = VBase4(0.75, 0.95, 0.75, 1.0) self.generateBody() self.generateHead('bigcheese') self.setHeight(9.34) elif dna.name == 'bf': self.scale = 4.0 / cSize self.handColor = SuitDNA.legalPolyColor self.generateBody() self.headTexture = 'bottom-feeder.jpg' self.generateHead('tightwad') self.setHeight(4.81) elif dna.name == 'b': self.scale = 4.375 / bSize self.handColor = VBase4(0.95, 0.95, 1.0, 1.0) self.generateBody() self.headTexture = 'blood-sucker.jpg' self.generateHead('movershaker') self.setHeight(6.17) elif dna.name == 'dt': self.scale = 4.25 / aSize self.handColor = SuitDNA.legalPolyColor self.generateBody() self.headTexture = 'double-talker.jpg' self.generateHead('twoface') self.setHeight(5.63) elif dna.name == 'ac': self.scale = 4.35 / bSize self.handColor = SuitDNA.legalPolyColor self.generateBody() self.generateHead('ambulancechaser') self.setHeight(6.39) elif dna.name == 'bs': self.scale = 4.5 / aSize self.handColor = SuitDNA.legalPolyColor self.generateBody() self.generateHead('backstabber') self.setHeight(6.71) elif dna.name == 'sd': self.scale = 5.65 / bSize self.handColor = VBase4(0.5, 0.8, 0.75, 1.0) self.generateBody() self.headTexture = 'spin-doctor.jpg' self.generateHead('telemarketer') self.setHeight(7.9) elif dna.name == 'le': self.scale = 7.125 / aSize self.handColor = VBase4(0.25, 0.25, 0.5, 1.0) self.generateBody() self.generateHead('legaleagle') self.setHeight(8.27) elif dna.name == 'bw': self.scale = 7.0 / aSize self.handColor = SuitDNA.legalPolyColor self.generateBody() self.generateHead('bigwig') self.setHeight(8.69) elif dna.name == 'sc': self.scale = 3.6 / cSize self.handColor = SuitDNA.moneyPolyColor self.generateBody() self.generateHead('coldcaller') self.setHeight(4.77) elif dna.name == 'pp': self.scale = 3.55 / aSize self.handColor = VBase4(1.0, 0.5, 0.6, 1.0) self.generateBody() self.generateHead('pennypincher') self.setHeight(5.26) elif dna.name == 'tw': self.scale = 4.5 / cSize self.handColor = SuitDNA.moneyPolyColor self.generateBody() self.generateHead('tightwad') self.setHeight(5.41) elif dna.name == 'bc': self.scale = 4.4 / bSize self.handColor = SuitDNA.moneyPolyColor self.generateBody() self.generateHead('beancounter') self.setHeight(5.95) elif dna.name == 'nc': self.scale = 5.25 / aSize self.handColor = SuitDNA.moneyPolyColor self.generateBody() self.generateHead('numbercruncher') self.setHeight(7.22) elif dna.name == 'mb': self.scale = 5.3 / cSize self.handColor = SuitDNA.moneyPolyColor self.generateBody() self.generateHead('moneybags') self.setHeight(6.97) elif dna.name == 'ls': self.scale = 6.5 / bSize self.handColor = VBase4(0.5, 0.85, 0.75, 1.0) self.generateBody() self.generateHead('loanshark') self.setHeight(8.58) elif dna.name == 'rb': self.scale = 7.0 / aSize self.handColor = SuitDNA.moneyPolyColor self.generateBody() self.headTexture = 'robber-baron.jpg' self.generateHead('yesman') self.setHeight(8.95) elif dna.name == 'cc': self.scale = 3.5 / cSize self.handColor = VBase4(0.55, 0.65, 1.0, 1.0) self.headColor = VBase4(0.25, 0.35, 1.0, 1.0) self.generateBody() self.generateHead('coldcaller') self.setHeight(4.63) elif dna.name == 'tm': self.scale = 3.75 / bSize self.handColor = SuitDNA.salesPolyColor self.generateBody() self.generateHead('telemarketer') self.setHeight(5.24) elif dna.name == 'nd': self.scale = 4.35 / aSize self.handColor = SuitDNA.salesPolyColor self.generateBody() self.headTexture = 'name-dropper.jpg' self.generateHead('numbercruncher') self.setHeight(5.98) elif dna.name == 'gh': self.scale = 4.75 / cSize self.handColor = SuitDNA.salesPolyColor self.generateBody() self.generateHead('gladhander') self.setHeight(6.4) elif dna.name == 'ms': self.scale = 4.75 / bSize self.handColor = SuitDNA.salesPolyColor self.generateBody() self.generateHead('movershaker') self.setHeight(6.7) elif dna.name == 'tf': self.scale = 5.25 / aSize self.handColor = SuitDNA.salesPolyColor self.generateBody() self.generateHead('twoface') self.setHeight(6.95) elif dna.name == 'm': self.scale = 5.75 / aSize self.handColor = SuitDNA.salesPolyColor self.generateBody() self.headTexture = 'mingler.jpg' self.generateHead('twoface') self.setHeight(7.61) elif dna.name == 'mh': self.scale = 7.0 / aSize self.handColor = SuitDNA.salesPolyColor self.generateBody() self.generateHead('yesman') self.setHeight(8.95) self.setName(SuitBattleGlobals.SuitAttributes[dna.name]['name']) self.getGeomNode().setScale(self.scale) self.generateHealthBar() self.generateCorporateMedallion() return def generateBody(self): animDict = self.generateAnimDict() filePrefix, bodyPhase = ModelDict[self.style.body] if base.config.GetBool('want-new-cogs', 0): if cogExists(filePrefix + 'zero.bam'): self.loadModel('phase_3.5' + filePrefix + 'zero') else: self.loadModel('phase_3.5' + filePrefix + 'mod') else: self.loadModel('phase_3.5' + filePrefix + 'mod') self.loadAnims(animDict) self.setSuitClothes() def generateAnimDict(self): animDict = {} filePrefix, bodyPhase = ModelDict[self.style.body] for anim in AllSuits: animDict[anim[0]] = 'phase_' + str(bodyPhase) + filePrefix + anim[1] for anim in AllSuitsMinigame: animDict[anim[0]] = 'phase_4' + filePrefix + anim[1] for anim in AllSuitsTutorialBattle: filePrefix, bodyPhase = TutorialModelDict[self.style.body] animDict[anim[0]] = 'phase_' + str(bodyPhase) + filePrefix + anim[1] for anim in AllSuitsBattle: animDict[anim[0]] = 'phase_5' + filePrefix + anim[1] if not base.config.GetBool('want-new-cogs', 0): if self.style.body == 'a': animDict['neutral'] = 'phase_4/models/char/suitA-neutral' for anim in SuitsCEOBattle: animDict[anim[0]] = 'phase_12/models/char/suitA-' + anim[1] elif self.style.body == 'b': animDict['neutral'] = 'phase_4/models/char/suitB-neutral' for anim in SuitsCEOBattle: animDict[anim[0]] = 'phase_12/models/char/suitB-' + anim[1] elif self.style.body == 'c': animDict['neutral'] = 'phase_3.5/models/char/suitC-neutral' for anim in SuitsCEOBattle: animDict[anim[0]] = 'phase_12/models/char/suitC-' + anim[1] try: animList = eval(self.style.name) except NameError: animList = () for anim in animList: phase = 'phase_' + str(anim[2]) animDict[anim[0]] = phase + filePrefix + anim[1] return animDict def initializeBodyCollisions(self, collIdStr): Avatar.Avatar.initializeBodyCollisions(self, collIdStr) if not self.ghostMode: self.collNode.setCollideMask(self.collNode.getIntoCollideMask() | ToontownGlobals.PieBitmask) def setSuitClothes(self, modelRoot = None): if not modelRoot: modelRoot = self dept = self.style.dept phase = 3.5 def __doItTheOldWay__(): torsoTex = loader.loadTexture('phase_%s/maps/%s_blazer.jpg' % (phase, dept)) torsoTex.setMinfilter(Texture.FTLinearMipmapLinear) torsoTex.setMagfilter(Texture.FTLinear) legTex = loader.loadTexture('phase_%s/maps/%s_leg.jpg' % (phase, dept)) legTex.setMinfilter(Texture.FTLinearMipmapLinear) legTex.setMagfilter(Texture.FTLinear) armTex = loader.loadTexture('phase_%s/maps/%s_sleeve.jpg' % (phase, dept)) armTex.setMinfilter(Texture.FTLinearMipmapLinear) armTex.setMagfilter(Texture.FTLinear) modelRoot.find('**/torso').setTexture(torsoTex, 1) modelRoot.find('**/arms').setTexture(armTex, 1) modelRoot.find('**/legs').setTexture(legTex, 1) modelRoot.find('**/hands').setColor(self.handColor) self.leftHand = self.find('**/joint_Lhold') self.rightHand = self.find('**/joint_Rhold') self.shadowJoint = self.find('**/joint_shadow') self.nametagJoint = self.find('**/joint_nameTag') if base.config.GetBool('want-new-cogs', 0): if dept == 'c': texType = 'bossbot' elif dept == 'm': texType = 'cashbot' elif dept == 'l': texType = 'lawbot' elif dept == 's': texType = 'sellbot' if self.find('**/body').isEmpty(): __doItTheOldWay__() else: filepath = 'phase_3.5/maps/tt_t_ene_' + texType + '.jpg' if cogExists('/maps/tt_t_ene_' + texType + '.jpg'): bodyTex = loader.loadTexture(filepath) self.find('**/body').setTexture(bodyTex, 1) self.leftHand = self.find('**/def_joint_left_hold') self.rightHand = self.find('**/def_joint_right_hold') self.shadowJoint = self.find('**/def_shadow') self.nametagJoint = self.find('**/def_nameTag') else: __doItTheOldWay__() def makeWaiter(self, modelRoot = None): if not modelRoot: modelRoot = self self.isWaiter = 1 torsoTex = loader.loadTexture('phase_3.5/maps/waiter_m_blazer.jpg') torsoTex.setMinfilter(Texture.FTLinearMipmapLinear) torsoTex.setMagfilter(Texture.FTLinear) legTex = loader.loadTexture('phase_3.5/maps/waiter_m_leg.jpg') legTex.setMinfilter(Texture.FTLinearMipmapLinear) legTex.setMagfilter(Texture.FTLinear) armTex = loader.loadTexture('phase_3.5/maps/waiter_m_sleeve.jpg') armTex.setMinfilter(Texture.FTLinearMipmapLinear) armTex.setMagfilter(Texture.FTLinear) modelRoot.find('**/torso').setTexture(torsoTex, 1) modelRoot.find('**/arms').setTexture(armTex, 1) modelRoot.find('**/legs').setTexture(legTex, 1) def makeRentalSuit(self, suitType, modelRoot = None): if not modelRoot: modelRoot = self.getGeomNode() if suitType == 's': torsoTex = loader.loadTexture('phase_3.5/maps/tt_t_ene_sellbotRental_blazer.jpg') legTex = loader.loadTexture('phase_3.5/maps/tt_t_ene_sellbotRental_leg.jpg') armTex = loader.loadTexture('phase_3.5/maps/tt_t_ene_sellbotRental_sleeve.jpg') handTex = loader.loadTexture('phase_3.5/maps/tt_t_ene_sellbotRental_hand.jpg') else: self.notify.warning('No rental suit for cog type %s' % suitType) return self.isRental = 1 modelRoot.find('**/torso').setTexture(torsoTex, 1) modelRoot.find('**/arms').setTexture(armTex, 1) modelRoot.find('**/legs').setTexture(legTex, 1) modelRoot.find('**/hands').setTexture(handTex, 1) def generateHead(self, headType): if base.config.GetBool('want-new-cogs', 0): filePrefix, phase = HeadModelDict[self.style.body] else: filePrefix, phase = ModelDict[self.style.body] headModel = loader.loadModel('phase_' + str(phase) + filePrefix + 'heads') headReferences = headModel.findAllMatches('**/' + headType) for i in xrange(0, headReferences.getNumPaths()): if base.config.GetBool('want-new-cogs', 0): headPart = self.instance(headReferences.getPath(i), 'modelRoot', 'to_head') if not headPart: headPart = self.instance(headReferences.getPath(i), 'modelRoot', 'joint_head') else: headPart = self.instance(headReferences.getPath(i), 'modelRoot', 'joint_head') if self.headTexture: headTex = loader.loadTexture('phase_' + str(phase) + '/maps/' + self.headTexture) headTex.setMinfilter(Texture.FTLinearMipmapLinear) headTex.setMagfilter(Texture.FTLinear) headPart.setTexture(headTex, 1) if self.headColor: headPart.setColor(self.headColor) self.headParts.append(headPart) headModel.removeNode() def generateCorporateTie(self, modelPath = None): if not modelPath: modelPath = self dept = self.style.dept tie = modelPath.find('**/tie') if tie.isEmpty(): self.notify.warning('skelecog has no tie model!!!') return if dept == 'c': tieTex = loader.loadTexture('phase_5/maps/cog_robot_tie_boss.jpg') elif dept == 's': tieTex = loader.loadTexture('phase_5/maps/cog_robot_tie_sales.jpg') elif dept == 'l': tieTex = loader.loadTexture('phase_5/maps/cog_robot_tie_legal.jpg') elif dept == 'm': tieTex = loader.loadTexture('phase_5/maps/cog_robot_tie_money.jpg') tieTex.setMinfilter(Texture.FTLinearMipmapLinear) tieTex.setMagfilter(Texture.FTLinear) tie.setTexture(tieTex, 1) def generateCorporateMedallion(self): icons = loader.loadModel('phase_3/models/gui/cog_icons') dept = self.style.dept if base.config.GetBool('want-new-cogs', 0): chestNull = self.find('**/def_joint_attachMeter') if chestNull.isEmpty(): chestNull = self.find('**/joint_attachMeter') else: chestNull = self.find('**/joint_attachMeter') if dept == 'c': self.corpMedallion = icons.find('**/CorpIcon').copyTo(chestNull) elif dept == 's': self.corpMedallion = icons.find('**/SalesIcon').copyTo(chestNull) elif dept == 'l': self.corpMedallion = icons.find('**/LegalIcon').copyTo(chestNull) elif dept == 'm': self.corpMedallion = icons.find('**/MoneyIcon').copyTo(chestNull) self.corpMedallion.setPosHprScale(0.02, 0.05, 0.04, 180.0, 0.0, 0.0, 0.51, 0.51, 0.51) self.corpMedallion.setColor(self.medallionColors[dept]) icons.removeNode() def generateHealthBar(self): self.removeHealthBar() model = loader.loadModel('phase_3.5/models/gui/matching_game_gui') button = model.find('**/minnieCircle') button.setScale(3.0) button.setH(180.0) button.setColor(self.healthColors[0]) if base.config.GetBool('want-new-cogs', 0): chestNull = self.find('**/def_joint_attachMeter') if chestNull.isEmpty(): chestNull = self.find('**/joint_attachMeter') else: chestNull = self.find('**/joint_attachMeter') button.reparentTo(chestNull) self.healthBar = button glow = BattleProps.globalPropPool.getProp('glow') glow.reparentTo(self.healthBar) glow.setScale(0.28) glow.setPos(-0.005, 0.01, 0.015) glow.setColor(self.healthGlowColors[0]) button.flattenLight() self.healthBarGlow = glow self.healthBar.hide() self.healthCondition = 0 def reseatHealthBarForSkele(self): self.healthBar.setPos(0.0, 0.1, 0.0) def updateHealthBar(self, hp, forceUpdate = 0): if hp > self.currHP: hp = self.currHP self.currHP -= hp health = float(self.currHP) / float(self.maxHP) if health > 0.95: condition = 0 elif health > 0.7: condition = 1 elif health > 0.3: condition = 2 elif health > 0.05: condition = 3 elif health > 0.0: condition = 4 else: condition = 5 if self.healthCondition != condition or forceUpdate: if condition == 4: blinkTask = Task.loop(Task(self.__blinkRed), Task.pause(0.75), Task(self.__blinkGray), Task.pause(0.1)) taskMgr.add(blinkTask, self.uniqueName('blink-task')) elif condition == 5: if self.healthCondition == 4: taskMgr.remove(self.uniqueName('blink-task')) blinkTask = Task.loop(Task(self.__blinkRed), Task.pause(0.25), Task(self.__blinkGray), Task.pause(0.1)) taskMgr.add(blinkTask, self.uniqueName('blink-task')) else: self.healthBar.setColor(self.healthColors[condition], 1) self.healthBarGlow.setColor(self.healthGlowColors[condition], 1) self.healthCondition = condition def __blinkRed(self, task): self.healthBar.setColor(self.healthColors[3], 1) self.healthBarGlow.setColor(self.healthGlowColors[3], 1) if self.healthCondition == 5: self.healthBar.setScale(1.17) return Task.done def __blinkGray(self, task): if not self.healthBar: return self.healthBar.setColor(self.healthColors[4], 1) self.healthBarGlow.setColor(self.healthGlowColors[4], 1) if self.healthCondition == 5: self.healthBar.setScale(1.0) return Task.done def removeHealthBar(self): if self.healthBar: self.healthBar.removeNode() self.healthBar = None if self.healthCondition == 4 or self.healthCondition == 5: taskMgr.remove(self.uniqueName('blink-task')) self.healthCondition = 0 return def getLoseActor(self): if base.config.GetBool('want-new-cogs', 0): if self.find('**/body'): return self if self.loseActor == None: if not self.isSkeleton: filePrefix, phase = TutorialModelDict[self.style.body] loseModel = 'phase_' + str(phase) + filePrefix + 'lose-mod' loseAnim = 'phase_' + str(phase) + filePrefix + 'lose' self.loseActor = Actor.Actor(loseModel, {'lose': loseAnim}) loseNeck = self.loseActor.find('**/joint_head') for part in self.headParts: part.instanceTo(loseNeck) if self.isWaiter: self.makeWaiter(self.loseActor) else: self.setSuitClothes(self.loseActor) else: loseModel = 'phase_5/models/char/cog' + string.upper(self.style.body) + '_robot-lose-mod' filePrefix, phase = TutorialModelDict[self.style.body] loseAnim = 'phase_' + str(phase) + filePrefix + 'lose' self.loseActor = Actor.Actor(loseModel, {'lose': loseAnim}) self.generateCorporateTie(self.loseActor) self.loseActor.setScale(self.scale) self.loseActor.setPos(self.getPos()) self.loseActor.setHpr(self.getHpr()) shadowJoint = self.loseActor.find('**/joint_shadow') dropShadow = loader.loadModel('phase_3/models/props/drop_shadow') dropShadow.setScale(0.45) dropShadow.setColor(0.0, 0.0, 0.0, 0.5) dropShadow.reparentTo(shadowJoint) return self.loseActor def cleanupLoseActor(self): self.notify.debug('cleanupLoseActor()') if self.loseActor != None: self.notify.debug('cleanupLoseActor() - got one') self.loseActor.cleanup() self.loseActor = None return def makeSkeleton(self): model = 'phase_5/models/char/cog' + string.upper(self.style.body) + '_robot-zero' anims = self.generateAnimDict() anim = self.getCurrentAnim() dropShadow = self.dropShadow if not dropShadow.isEmpty(): dropShadow.reparentTo(hidden) self.removePart('modelRoot') self.loadModel(model) self.loadAnims(anims) self.getGeomNode().setScale(self.scale * 1.0173) self.generateHealthBar() self.generateCorporateMedallion() self.generateCorporateTie() self.setHeight(self.height) parts = self.findAllMatches('**/pPlane*') for partNum in xrange(0, parts.getNumPaths()): bb = parts.getPath(partNum) bb.setTwoSided(1) self.setName(TTLocalizer.Skeleton) nameInfo = TTLocalizer.SuitBaseNameWithLevel % {'name': self.name, 'dept': self.getStyleDept(), 'level': self.getActualLevel()} self.setDisplayName(nameInfo) self.leftHand = self.find('**/joint_Lhold') self.rightHand = self.find('**/joint_Rhold') self.shadowJoint = self.find('**/joint_shadow') self.nametagNull = self.find('**/joint_nameTag') if not dropShadow.isEmpty(): dropShadow.setScale(0.75) if not self.shadowJoint.isEmpty(): dropShadow.reparentTo(self.shadowJoint) self.loop(anim) self.isSkeleton = 1 def getHeadParts(self): return self.headParts def getRightHand(self): return self.rightHand def getLeftHand(self): return self.leftHand def getShadowJoint(self): return self.shadowJoint def getNametagJoints(self): return [] def getDialogueArray(self): if self.isSkeleton: loadSkelDialog() return SkelSuitDialogArray else: return SuitDialogArray # okay decompyling C:\Users\Maverick\Documents\Visual Studio 2010\Projects\Unfreezer\py2\toontown\suit\Suit.pyc # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2013.08.22 22:25:34 Pacific Daylight Time
{ "repo_name": "ToonTownInfiniteRepo/ToontownInfinite", "path": "toontown/suit/Suit.py", "copies": "1", "size": "38666", "license": "mit", "hash": 797889818532806900, "line_mean": 37.0570866142, "line_max": 119, "alpha_frac": 0.571277091, "autogenerated": false, "ratio": 3.270128552097429, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4341405643097429, "avg_score": null, "num_lines": null }
# 2013.09.29 18:39:30 W. Europe Daylight Time # Embedded file name: scripts/client/messenger/gui/Scaleform/channels/bw_battle_controllers.py import BattleReplay from LanguageFilterControll import testIfEnglish from debug_utils import LOG_DEBUG, LOG_ERROR from gui.BattleContext import g_battleContext from gui.shared import g_eventBus, EVENT_BUS_SCOPE from gui.shared.events import MessengerEvent from helpers import i18n from messenger import g_settings from messenger.gui.Scaleform.view.BattleChannelView import BattleChannelView from messenger.gui.interfaces import IChannelController from messenger.m_constants import BATTLE_CHANNEL, PROTO_TYPE, MESSENGER_I18N_FILE from messenger.ext.player_helpers import isCurrentPlayer from messenger.proto import proto_getter from messenger.proto.bw import cooldown, entities from messenger.storage import storage_getter class _ChannelController(IChannelController): _teamChannel = entities.BWChannelLightEntity(-1) def __init__(self, channel): super(_ChannelController, self).__init__() self._channel = channel channel.onConnectStateChanged += self._onConnectStateChanged self._view = None return def __del__(self): LOG_DEBUG('Channel controller deleted:', self) @proto_getter(PROTO_TYPE.BW) def proto(self): return None def getChannel(self): return self._channel def setView(self, view): if self._view: LOG_ERROR('View is defined', self._view) elif isinstance(view, BattleChannelView): self._view = view self._view.setController(self) else: LOG_ERROR('View must be extends BattleEntry', self._view) def removeView(self): if self._view is not None: self._view.removeController() self._view = None return def clear(self): self._channel.onConnectStateChanged -= self._onConnectStateChanged self._channel = None self.removeView() return def activate(self): self._onConnectStateChanged(self._channel) def getFullPlayerName(self, chatAction): return g_battleContext.getFullPlayerName(accID=chatAction.originator) def getMessageColors(self, message): return (g_settings.getColorScheme('battle/player').getHexStr('unknown'), g_settings.getColorScheme('battle/message').getHexStr('unknown')) def canSendMessage(self): result, errorMsg = True, '' if cooldown.isBroadcatInCooldown(): result, errorMsg = False, cooldown.BROADCAST_COOL_DOWN_MESSAGE return (result, errorMsg) def sendMessage(self, message): result, errorMsg = self.canSendMessage() if result: self.proto.channels.sendMessage(self._channel.getID(), message) else: self._view.addMessage(g_settings.htmlTemplates.format('battleErrorMessage', ctx={'error': errorMsg})) return result def addMessage(self, message, doFormatting = True): isCurrent = isCurrentPlayer(message.originator) if doFormatting: text = self._format(message, message.data) else: text = message.data """ if testIfEnglish(message.data): text = text + " en" else: text = text + " nonEn" """ if testIfEnglish(message.data): self._channel.addMessage(text) if self._view: self._view.addMessage(text, isCurrentPlayer=isCurrent) if BattleReplay.g_replayCtrl.isRecording: BattleReplay.g_replayCtrl.onBattleChatMessage(text, isCurrent) return True def addCommand(self, command): cmdData = command.getProtoData() isCurrent = isCurrentPlayer(cmdData.originator) text = self._format(cmdData, command.getCommandText()) if BattleReplay.g_replayCtrl.isRecording: BattleReplay.g_replayCtrl.onBattleChatMessage(text, isCurrent) if self._view: self._view.addMessage(text, isCurrentPlayer=isCurrent) def _format(self, chatAction, msgText): playerColor, msgColor = self.getMessageColors(chatAction) return g_settings.battle.messageFormat % {'playerColor': playerColor, 'playerName': unicode(self.getFullPlayerName(chatAction), 'utf-8', errors='ignore'), 'messageColor': msgColor, 'messageText': msgText} def _onConnectStateChanged(self, channel): pass class TeamChannelController(_ChannelController): def __init__(self, channel): super(TeamChannelController, self).__init__(channel) _ChannelController._teamChannel.setID(channel.getID()) def __del__(self): self._teamChannel.setID(-1) super(TeamChannelController, self).__del__() def getMessageColors(self, message): dbID = message.originator mColor = g_settings.getColorScheme('battle/message').getHexStr('team') pColorScheme = g_settings.getColorScheme('battle/player') pColor = pColorScheme.getHexStr('teammate') if isCurrentPlayer(dbID): pColor = pColorScheme.getHexStr('himself') elif g_battleContext.isTeamKiller(accID=dbID): pColor = pColorScheme.getHexStr('teamkiller') elif g_battleContext.isSquadMan(accID=dbID): pColor = pColorScheme.getHexStr('squadman') return (pColor, mColor) def _onConnectStateChanged(self, channel): if channel.isJoined(): g_eventBus.handleEvent(MessengerEvent(MessengerEvent.BATTLE_CHANNEL_CTRL_INITED, {'settings': BATTLE_CHANNEL.TEAM, 'controller': self}), scope=EVENT_BUS_SCOPE.BATTLE) class CommonChannelController(_ChannelController): __i18n_ally = i18n.makeString('#{0:>s}:battle/unknown/ally'.format(MESSENGER_I18N_FILE)) __i18n_enemy = i18n.makeString('#{0:>s}:battle/unknown/enemy'.format(MESSENGER_I18N_FILE)) @storage_getter('channels') def channelsStorage(self): return None def getFullPlayerName(self, chatAction): fullName = g_battleContext.getFullPlayerName(accID=chatAction.originator) if not len(fullName): channel = self.channelsStorage.getChannel(self._teamChannel) if channel and channel.hasMember(chatAction.originator): fullName = self.__i18n_ally else: fullName = self.__i18n_enemy return fullName def getMessageColors(self, message): dbID = message.originator mColor = g_settings.getColorScheme('battle/message').getHexStr('common') pColorScheme = g_settings.getColorScheme('battle/player') pColor = pColorScheme.getHexStr('unknown') if isCurrentPlayer(dbID): pColor = pColorScheme.getHexStr('himself') else: channel = self.channelsStorage.getChannel(self._teamChannel) if channel and channel.hasMember(dbID): if g_battleContext.isTeamKiller(accID=dbID): pColor = pColorScheme.getHexStr('teamkiller') elif g_battleContext.isSquadMan(accID=dbID): pColor = pColorScheme.getHexStr('squadman') else: pColor = pColorScheme.getHexStr('teammate') elif self._channel.hasMember(dbID): pColor = pColorScheme.getHexStr('enemy') return (pColor, mColor) def _onConnectStateChanged(self, channel): if channel.isJoined(): g_eventBus.handleEvent(MessengerEvent(MessengerEvent.BATTLE_CHANNEL_CTRL_INITED, {'settings': BATTLE_CHANNEL.COMMON, 'controller': self}), scope=EVENT_BUS_SCOPE.BATTLE) class SquadChannelController(_ChannelController): def __init__(self, channel): super(SquadChannelController, self).__init__(channel) def addMessage(self, message, doFormatting = True): isCurrent = isCurrentPlayer(message.originator) if doFormatting: text = self._format(message, message.data) else: text = message.data if BattleReplay.g_replayCtrl.isRecording: BattleReplay.g_replayCtrl.onBattleChatMessage(text, isCurrent) if self._view: self._view.addMessage(text, isCurrentPlayer=isCurrent) return True def getFullPlayerName(self, chatAction): pName = None try: pName = chatAction.originatorNickName.encode('utf-8') except UnicodeError: LOG_ERROR('Can not encode nick name', chatAction) return g_battleContext.getFullPlayerName(accID=chatAction.originator, pName=pName) def getMessageColors(self, message): dbID = message.originator mColor = g_settings.getColorScheme('battle/message').getHexStr('squad') pColorScheme = g_settings.getColorScheme('battle/player') pColor = pColorScheme.getHexStr('squadman') if isCurrentPlayer(dbID): pColor = pColorScheme.getHexStr('himself') elif g_battleContext.isTeamKiller(accID=dbID): pColor = pColorScheme.getHexStr('teamkiller') return (pColor, mColor) def _onConnectStateChanged(self, channel): if channel.isJoined(): g_eventBus.handleEvent(MessengerEvent(MessengerEvent.BATTLE_CHANNEL_CTRL_INITED, {'settings': BATTLE_CHANNEL.SQUAD, 'controller': self}), scope=EVENT_BUS_SCOPE.BATTLE) def addDefMessage(message): mColor = g_settings.getColorScheme('battle/message').getHexStr('unknown') pColor = g_settings.getColorScheme('battle/player').getHexStr('unknown') return g_settings.battle.messageFormat % {'playerColor': pColor, 'playerName': unicode(g_battleContext.getFullPlayerName(accID=message.originator), 'utf-8', errors='ignore'), 'messageColor': mColor, 'messageText': message.data}
{ "repo_name": "sgoldenb/siemafilter", "path": "src/bw_battle_controllers.py", "copies": "1", "size": "9917", "license": "mit", "hash": -443908975520755600, "line_mean": 38.3531746032, "line_max": 146, "alpha_frac": 0.6641121307, "autogenerated": false, "ratio": 3.8542557326078506, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5018367863307851, "avg_score": null, "num_lines": null }
# 2013-2014 Massachusetts Open Cloud Contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS # IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either # express or implied. See the License for the specific language # governing permissions and limitations under the License. """This module provides the HaaS service's public API. TODO: Spec out and document what sanitization is required. """ import importlib import json from schema import Schema, Optional from haas import model from haas.config import cfg from haas.rest import rest_call from haas.class_resolver import concrete_class_for from haas.network_allocator import get_network_allocator from haas.errors import * @rest_call('PUT', '/user/<user>') def user_create(user, password): """Create user with given password. If the user already exists, a DuplicateError will be raised. """ db = model.Session() _assert_absent(db, model.User, user) user = model.User(user, password) db.add(user) db.commit() @rest_call('DELETE', '/user/<user>') def user_delete(user): """Delete user. If the user does not exist, a NotFoundError will be raised. """ db = model.Session() user = _must_find(db, model.User, user) db.delete(user) db.commit() # Project Code # ################ @rest_call('GET', '/projects') def list_projects(): """List all projects. Returns a JSON array of strings representing a list of projects. Example: '["project1", "project2", "project3"]' """ db = model.Session() projects = db.query(model.Project).all() projects = [p.label for p in projects] return json.dumps(projects) @rest_call('PUT', '/project/<project>') def project_create(project): """Create a project. If the project already exists, a DuplicateError will be raised. """ db = model.Session() _assert_absent(db, model.Project, project) project = model.Project(project) db.add(project) db.commit() @rest_call('DELETE', '/project/<project>') def project_delete(project): """Delete project. If the project does not exist, a NotFoundError will be raised. """ db = model.Session() project = _must_find(db, model.Project, project) if project.nodes: raise BlockedError("Project has nodes still") if project.networks_created: raise BlockedError("Project still has networks") if project.networks_access: ### FIXME: This is not the user's fault, and they cannot fix it. The ### only reason we need to error here is that, with how network access ### is done, the following bad thing happens. If there's a network ### that only the project can access, its "access" field will be the ### project. When you then delete that project, "access" will be set ### to None instead. Counter-intuitively, this then makes that ### network accessible to ALL PROJECTS! Once we use real ACLs, this ### will not be an issue---instead, the network will be accessible by ### NO projects. raise BlockedError("Project can still access networks") if project.headnodes: raise BlockedError("Project still has a headnode") db.delete(project) db.commit() @rest_call('POST', '/project/<project>/connect_node') def project_connect_node(project, node): """Add a node to a project. If the node or project does not exist, a NotFoundError will be raised. If node is already owned by a project, a BlockedError will be raised. """ db = model.Session() project = _must_find(db, model.Project, project) node = _must_find(db, model.Node, node) if node.project is not None: raise BlockedError("Node is already owned by a project.") project.nodes.append(node) db.commit() @rest_call('POST', '/project/<project>/detach_node') def project_detach_node(project, node): """Remove a node from a project. If the node or project does not exist, a NotFoundError will be raised. """ db = model.Session() project = _must_find(db, model.Project, project) node = _must_find(db, model.Node, node) if node not in project.nodes: raise NotFoundError("Node not in project") num_attachments = db.query(model.NetworkAttachment)\ .filter(model.Nic.owner == node, model.NetworkAttachment.nic_id == model.Nic.id).count() if num_attachments != 0: raise BlockedError("Node attached to a network") for nic in node.nics: if nic.current_action is not None: raise BlockedError("Node has pending network actions") node.obm.stop_console() node.obm.delete_console() project.nodes.remove(node) db.commit() @rest_call('POST', '/project/<project>/add_user') def project_add_user(project, user): """Add a user to a project. If the project or user does not exist, a NotFoundError will be raised. """ db = model.Session() user = _must_find(db, model.User, user) project = _must_find(db, model.Project, project) if project in user.projects: raise DuplicateError('User %s is already in project %s'% (user.label, project.label)) user.projects.append(project) db.commit() @rest_call('POST', '/project/<project>/remove_user') def project_remove_user(project, user): """Remove a user from a project. If the project or user does not exist, a NotFoundError will be raised. """ db = model.Session() user = _must_find(db, model.User, user) project = _must_find(db, model.Project, project) if project not in user.projects: raise NotFoundError("User %s is not in project %s"% (user.label, project.label)) user.projects.remove(project) db.commit() # Node Code # ############# @rest_call('PUT', '/node/<node>', schema=Schema({ 'obm':{ 'type': basestring, Optional(object):object, }, })) def node_register(node, **kwargs): """Create node. If the node already exists, a DuplicateError will be raised. """ db = model.Session() _assert_absent(db, model.Node, node) obm_type = kwargs['obm']['type'] cls = concrete_class_for(model.Obm, obm_type) if cls is None: raise BadArgumentError('%r is not a valid OBM type.' % obm_type) cls.validate(kwargs['obm']) node_obj = model.Node(label=node, obm=cls(**kwargs['obm'])) db.add(node_obj) db.commit() @rest_call('POST', '/node/<node>/power_cycle') def node_power_cycle(node): db = model.Session() node = _must_find(db, model.Node, node) node.obm.power_cycle() @rest_call('DELETE', '/node/<node>') def node_delete(node): """Delete node. If the node does not exist, a NotFoundError will be raised. """ db = model.Session() node = _must_find(db, model.Node, node) if node.nics != []: raise BlockedError("Node %r has nics; remove them before deleting %r.", (node.label, node.label)) node.obm.stop_console() node.obm.delete_console() db.delete(node) db.commit() @rest_call('PUT', '/node/<node>/nic/<nic>') def node_register_nic(node, nic, macaddr): """Register exitence of nic attached to given node. If the node does not exist, a NotFoundError will be raised. If there is already an nic with that name, a DuplicateError will be raised. """ db = model.Session() node = _must_find(db, model.Node, node) _assert_absent_n(db, node, model.Nic, nic) nic = model.Nic(node, nic, macaddr) db.add(nic) db.commit() @rest_call('DELETE', '/node/<node>/nic/<nic>') def node_delete_nic(node, nic): """Delete nic with given name. If the nic does not exist, a NotFoundError will be raised. """ db = model.Session() nic = _must_find_n(db, _must_find(db, model.Node, node), model.Nic, nic) db.delete(nic) db.commit() @rest_call('POST', '/node/<node>/nic/<nic>/connect_network', schema=Schema({ 'network' : basestring, Optional('channel'): basestring, })) def node_connect_network(node, nic, network, channel=None): """Connect a physical NIC to a network, on channel. If channel is ``None``, use the allocator default. Raises ProjectMismatchError if the node is not in a project, or if the project does not have access rights to the given network. Raises BlockedError if there is a pending network action, or if the network is already attached to the nic, or if the channel is in use. Raises BadArgumentError if the channel is invalid for the network. """ def _have_attachment(db, nic, query): """Return whether there are any attachments matching ``query`` for ``nic``. ``query`` should an argument suitable to pass to db.query(...).filter """ return db.query(model.NetworkAttachment).filter( model.NetworkAttachment.nic == nic, query, ).count() != 0 db = model.Session() node = _must_find(db, model.Node, node) nic = _must_find_n(db, node, model.Nic, nic) network = _must_find(db, model.Network, network) if not node.project: raise ProjectMismatchError("Node not in project") project = node.project allocator = get_network_allocator() if nic.current_action: raise BlockedError("A networking operation is already active on the nic.") if (network.access is not None) and (network.access is not project): raise ProjectMismatchError("Project does not have access to given network.") if _have_attachment(db, nic, model.NetworkAttachment.network == network): raise BlockedError("The network is already attached to the nic.") if channel is None: channel = allocator.get_default_channel(db) if _have_attachment(db, nic, model.NetworkAttachment.channel == channel): raise BlockedError("The channel is already in use on the nic.") if not allocator.is_legal_channel_for(db, channel, network.network_id): raise BadArgumentError("Channel %r, is not legal for this network." % channel) db.add(model.NetworkingAction(nic=nic, new_network=network, channel=channel)) db.commit() return '', 202 @rest_call('POST', '/node/<node>/nic/<nic>/detach_network') def node_detach_network(node, nic, network): """Detach network ``network`` from physical nic ``nic``. Raises ProjectMismatchError if the node is not in a project. Raises BlockedError if there is already a pending network action. Raises BadArgumentError if the network is not attached to the nic. """ db = model.Session() node = _must_find(db, model.Node, node) network = _must_find(db, model.Network, network) nic = _must_find_n(db, node, model.Nic, nic) if not node.project: raise ProjectMismatchError("Node not in project") if nic.current_action: raise BlockedError("A networking operation is already active on the nic.") attachment = db.query(model.NetworkAttachment)\ .filter_by(nic=nic, network=network).first() if attachment is None: raise BadArgumentError("The network is not attached to the nic.") db.add(model.NetworkingAction(nic=nic, channel=attachment.channel, new_network=None)) db.commit() return '', 202 # Head Node Code # ################## @rest_call('PUT', '/headnode/<headnode>') def headnode_create(headnode, project, base_img): """Create headnode. If a node with the same name already exists, a DuplicateError will be raised. If the project already has a headnode, a DuplicateError will be raised. If the project does not exist, a NotFoundError will be raised. """ valid_imgs = cfg.get('headnode', 'base_imgs') valid_imgs = [img.strip() for img in valid_imgs.split(',')] if base_img not in valid_imgs: raise BadArgumentError('Provided image is not a valid image.') db = model.Session() _assert_absent(db, model.Headnode, headnode) project = _must_find(db, model.Project, project) headnode = model.Headnode(project, headnode, base_img) db.add(headnode) db.commit() @rest_call('DELETE', '/headnode/<headnode>') def headnode_delete(headnode): """Delete headnode. If the node does not exist, a NotFoundError will be raised. """ db = model.Session() headnode = _must_find(db, model.Headnode, headnode) if not headnode.dirty: headnode.delete() for hnic in headnode.hnics: db.delete(hnic) db.delete(headnode) db.commit() @rest_call('POST', '/headnode/<headnode>/start') def headnode_start(headnode): """Start the headnode. This actually boots up the headnode virtual machine. The VM is created within libvirt if needed. Once the VM has been started once, it is "frozen," and all other headnode-related api calls will fail (by raising an IllegalStateError), with the exception of headnode_stop. """ db = model.Session() headnode = _must_find(db, model.Headnode, headnode) if headnode.dirty: headnode.create() headnode.start() db.commit() @rest_call('POST', '/headnode/<headnode>/stop') def headnode_stop(headnode): """Stop the headnode. This powers off the headnode. This is a hard poweroff; the VM is not given the opportunity to shut down cleanly. This does *not* unfreeze the VM; headnode_start will be the only valid API call after the VM is powered off. """ db = model.Session() headnode = _must_find(db, model.Headnode, headnode) headnode.stop() @rest_call('PUT', '/headnode/<headnode>/hnic/<hnic>') def headnode_create_hnic(headnode, hnic): """Create hnic attached to given headnode. If the node does not exist, a NotFoundError will be raised. If there is already an hnic with that name, a DuplicateError will be raised. """ db = model.Session() headnode = _must_find(db, model.Headnode, headnode) _assert_absent_n(db, headnode, model.Hnic, hnic) if not headnode.dirty: raise IllegalStateError hnic = model.Hnic(headnode, hnic) db.add(hnic) db.commit() @rest_call('DELETE', '/headnode/<headnode>/hnic/<hnic>') def headnode_delete_hnic(headnode, hnic): """Delete hnic on a given headnode. If the hnic does not exist, a NotFoundError will be raised. """ db = model.Session() headnode = _must_find(db, model.Headnode, headnode) hnic = _must_find_n(db, headnode, model.Hnic, hnic) if not headnode.dirty: raise IllegalStateError if not hnic: raise NotFoundError("Hnic: " + hnic.label) db.delete(hnic) db.commit() @rest_call('POST', '/headnode/<headnode>/hnic/<hnic>/connect_network') def headnode_connect_network(headnode, hnic, network): """Connect a headnode's hnic to a network. Raises IllegalStateError if the headnode has already been started. Raises ProjectMismatchError if the project does not have access rights to the given network. Raises BadArgumentError if the network is a non-allocated network. This is currently unsupported due to an implementation limitation, but will be supported in a future release. See issue #333. """ db = model.Session() headnode = _must_find(db, model.Headnode, headnode) hnic = _must_find_n(db, headnode, model.Hnic, hnic) network = _must_find(db, model.Network, network) if not network.allocated: raise BadArgumentError("Headnodes may only be connected to networks " "allocated by the project.") if not headnode.dirty: raise IllegalStateError project = headnode.project if (network.access is not None) and (network.access is not project): raise ProjectMismatchError("Project does not have access to given network.") hnic.network = network db.commit() @rest_call('POST', '/headnode/<headnode>/hnic/<hnic>/detach_network') def headnode_detach_network(headnode, hnic): """Detach a heanode's nic from any network it's on. Raises IllegalStateError if the headnode has already been started. """ db = model.Session() headnode = _must_find(db, model.Headnode, headnode) hnic = _must_find_n(db, headnode, model.Hnic, hnic) if not headnode.dirty: raise IllegalStateError hnic.network = None db.commit() # Network Code # ################ @rest_call('PUT', '/network/<network>') def network_create(network, creator, access, net_id): """Create a network. If the network with that name already exists, a DuplicateError will be raised. If the combination of creator, access, and net_id is illegal, a BadArgumentError will be raised. If network ID allocation was requested, and the network cannot be allocated (due to resource exhaustion), an AllocationError will be raised. Pass 'admin' as creator for an administrator-owned network. Pass '' as access for a publicly accessible network. Pass '' as net_id if you wish to use the HaaS's network-id allocation pool. Details of the various combinations of network attributes are in docs/networks.md """ db = model.Session() _assert_absent(db, model.Network, network) # Check legality of arguments, and find correct 'access' and 'creator' if creator != "admin": # Project-owned network if access != creator: raise BadArgumentError("Project-created networks must be accessed only by that project.") if net_id != "": raise BadArgumentError("Project-created networks must use network ID allocation") creator = _must_find(db, model.Project, creator) access = _must_find(db, model.Project, access) else: # Administrator-owned network creator = None if access == "": access = None else: access = _must_find(db, model.Project, access) # Allocate net_id, if requested if net_id == "": net_id = get_network_allocator().get_new_network_id(db) if net_id is None: raise AllocationError('No more networks') allocated = True else: allocated = False network = model.Network(creator, access, allocated, net_id, network) db.add(network) db.commit() @rest_call('DELETE', '/network/<network>') def network_delete(network): """Delete network. If the network does not exist, a NotFoundError will be raised. """ db = model.Session() network = _must_find(db, model.Network, network) if len(network.attachments) != 0: raise BlockedError("Network still connected to nodes") if network.hnics: raise BlockedError("Network still connected to headnodes") if len(network.scheduled_nics) != 0: raise BlockedError("There are pending actions on this network") if network.allocated: get_network_allocator().free_network_id(db, network.network_id) db.delete(network) db.commit() @rest_call('GET', '/network/<network>') def show_network(network): """Show details of a network. Returns a JSON object representing a network. The object will have at least the following fields: * "name", the name/label of the network (string). * "creator", the name of the project which created the network, or "admin", if it was created by an administrator. * "channels", a list of channels to which the network may be attached. It may also have the fields: * "access" -- if this is present, it is the name of the project which has access to the network. Otherwise, the network is public. """ db = model.Session() allocator = get_network_allocator() network = _must_find(db, model.Network, network) result = { 'name': network.label, 'channels': allocator.legal_channels_for(db, network.network_id), } if network.creator is None: result['creator'] = 'admin' else: result['creator'] = network.creator.label if network.access is not None: result['access'] = network.access.label return json.dumps(result) @rest_call('PUT', '/switch/<switch>', schema=Schema({ 'type': basestring, Optional(object): object, })) def switch_register(switch, type, **kwargs): db = model.Session() _assert_absent(db, model.Switch, switch) cls = concrete_class_for(model.Switch, type) if cls is None: raise BadArgumentError('%r is not a valid switch type.' % type) cls.validate(kwargs) obj = cls(**kwargs) obj.label = switch obj.type = type db.add(obj) db.commit() @rest_call('DELETE', '/switch/<switch>') def switch_delete(switch): db = model.Session() switch = _must_find(db, model.Switch, switch) if switch.ports != []: raise BlockedError("Switch %r has ports; delete them first." % switch.label) db.delete(switch) db.commit() @rest_call('PUT', '/switch/<switch>/port/<path:port>') def switch_register_port(switch, port): """Register a port on a switch. If the port already exists, a DuplicateError will be raised. """ db = model.Session() switch = _must_find(db, model.Switch, switch) _assert_absent_n(db, switch, model.Port, port) port = model.Port(port, switch) db.add(port) db.commit() @rest_call('DELETE', '/switch/<switch>/port/<path:port>') def switch_delete_port(switch, port): """Delete a port on a switch. If the port does not exist, a NotFoundError will be raised. """ db = model.Session() switch = _must_find(db, model.Switch, switch) port = _must_find_n(db, switch, model.Port, port) if port.nic is not None: raise BlockedError("Port %r is attached to a nic; please detach " "it first." % port.label) db.delete(port) db.commit() @rest_call('POST', '/switch/<switch>/port/<path:port>/connect_nic') def port_connect_nic(switch, port, node, nic): """Connect a port on a switch to a nic on a node. If any of the three arguments does not exist, a NotFoundError will be raised. If the port or the nic is already connected to something, a DuplicateError will be raised. """ db = model.Session() switch = _must_find(db, model.Switch, switch) port = _must_find_n(db, switch, model.Port, port) node = _must_find(db, model.Node, node) nic = _must_find_n(db, node, model.Nic, nic) if nic.port is not None: raise DuplicateError(nic.label) if port.nic is not None: raise DuplicateError(port.label) nic.port = port db.commit() @rest_call('POST', '/switch/<switch>/port/<path:port>/detach_nic') def port_detach_nic(switch, port): """Detach a port from the nic it's attached to If the port does not exist, a NotFoundError will be raised. If the port is not connected to anything, a NotFoundError will be raised. If the port is attached to a node which is not free, a BlockedError will be raised. """ db = model.Session() switch = _must_find(db, model.Switch, switch) port = _must_find_n(db, switch, model.Port, port) if port.nic is None: raise NotFoundError(port.label + " not attached") if port.nic.owner.project is not None: raise BlockedError("The port is attached to a node which is not free") port.nic = None db.commit() @rest_call('GET', '/free_nodes') def list_free_nodes(): """List all nodes not in any project. Returns a JSON array of strings representing a list of nodes. Example: '["node1", "node2", "node3"]' """ db = model.Session() nodes = db.query(model.Node).filter_by(project_id=None).all() nodes = [n.label for n in nodes] return json.dumps(nodes) @rest_call('GET', '/project/<project>/nodes') def list_project_nodes(project): """List all nodes belonging the given project. Returns a JSON array of strings representing a list of nodes. Example: '["node1", "node2", "node3"]' """ db = model.Session() project = _must_find(db, model.Project, project) nodes = project.nodes nodes = [n.label for n in nodes] return json.dumps(nodes) @rest_call('GET', '/project/<project>/networks') def list_project_networks(project): """List all private networks the project can access. Returns a JSON array of strings representing a list of networks. Example: '["net1", "net2", "net3"]' """ db = model.Session() project = _must_find(db, model.Project, project) networks = project.networks_access networks = [n.label for n in networks] return json.dumps(networks) @rest_call('GET', '/node/<nodename>') def show_node(nodename): """Show details of a node. Returns a JSON object representing a node. The object will have at least the following fields: * "name", the name/label of the node (string). * "free", indicates whether the node is free or has been allocated to a project. * "nics", a list of nics, each represted by a JSON object having at least the following fields: - "label", the nic's label. - "macaddr", the nic's mac address. Example: '{"name": "node1", "free": True, "nics": [{"label": "nic1", "macaddr": "01:23:45:67:89"}, {"label": "nic2", "macaddr": "12:34:56:78:90"}] }' """ db = model.Session() node = _must_find(db, model.Node, nodename) return json.dumps({ 'name': node.label, 'free': node.project_id is None, 'nics': [{'label': n.label, 'macaddr': n.mac_addr, } for n in node.nics], }) @rest_call('GET', '/project/<project>/headnodes') def list_project_headnodes(project): """List all headnodes belonging the given project. Returns a JSON array of strings representing a list of headnodes. Example: '["headnode1", "headnode2", "headnode3"]' """ db = model.Session() project = _must_find(db, model.Project, project) headnodes = project.headnodes headnodes = [hn.label for hn in headnodes] return json.dumps(headnodes) @rest_call('GET', '/headnode/<nodename>') def show_headnode(nodename): """Show details of a headnode. Returns a JSON object representing a headnode. The obect will have at least the following fields: * "name", the name/label of the headnode (string). * "project", the project to which the headnode belongs. * "hnics", a JSON array of hnic labels that are attached to this headnode. * "vncport", the vnc port that the headnode VM is listening on; this value can be None if the VM is powered off or has not been created yet. Example: '{"name": "headnode1", "project": "project1", "hnics": ["hnic1", "hnic2"], "vncport": 5900 }' """ db = model.Session() headnode = _must_find(db, model.Headnode, nodename) return json.dumps({ 'name': headnode.label, 'project': headnode.project.label, 'hnics': [n.label for n in headnode.hnics], 'vncport': headnode.get_vncport(), }) @rest_call('GET', '/headnode_images/') def list_headnode_images(): """Show headnode images listed in config file. Returns a JSON array of strings representing a list of headnode images. Example: '["headnode1.img", "headnode2.img", "headnode3.img"]' """ valid_imgs = cfg.get('headnode', 'base_imgs') valid_imgs = [img.strip() for img in valid_imgs.split(',')] return json.dumps(valid_imgs) # Console code # ################ @rest_call('GET', '/node/<nodename>/console') def show_console(nodename): """Show the contents of the console log.""" db = model.Session() node = _must_find(db, model.Node, nodename) log = node.obm.get_console() if log is None: raise NotFoundError('The console log for %s ' 'does not exist.' % nodename) return log @rest_call('PUT', '/node/<nodename>/console') def start_console(nodename): """Start logging output from the console.""" db = model.Session() node = _must_find(db, model.Node, nodename) node.obm.start_console() @rest_call('DELETE', '/node/<nodename>/console') def stop_console(nodename): """Stop logging output from the console and delete the log.""" db = model.Session() node = _must_find(db, model.Node, nodename) node.obm.stop_console() node.obm.delete_console() # Helper functions # #################### def _assert_absent(session, cls, name): """Raises a DuplicateError if the given object is already in the database. This is useful for most of the *_create functions. Arguments: session - a sqlaclhemy session to use. cls - the class of the object to query. name - the name of the object in question. """ obj = session.query(cls).filter_by(label=name).first() if obj: raise DuplicateError("%s %s already exists." % (cls.__name__, name)) def _must_find(session, cls, name): """Raises a NotFoundError if the given object doesn't exist in the datbase. Otherwise returns the object This is useful for most of the *_delete functions. Arguments: session - a sqlaclhemy session to use. cls - the class of the object to query. name - the name of the object in question. """ obj = session.query(cls).filter_by(label=name).first() if not obj: raise NotFoundError("%s %s does not exist." % (cls.__name__, name)) return obj def _namespaced_query(session, obj_outer, cls_inner, name_inner): """Helper function to search for subobjects of an object.""" return session.query(cls_inner) \ .filter_by(owner = obj_outer) \ .filter_by(label = name_inner).first() def _assert_absent_n(session, obj_outer, cls_inner, name_inner): """Raises DuplicateError if a "namespaced" object, such as a node's nic, exists. Otherwise returns successfully. Arguments: session - a SQLAlchemy session to use. obj_outer - the "owner" object cls_inner - the "owned" class name_inner - the name of the "owned" object """ obj_inner = _namespaced_query(session, obj_outer, cls_inner, name_inner) if obj_inner is not None: raise DuplicateError("%s %s on %s %s already exists" % (cls_inner.__name__, name_inner, obj_outer.__class__.__name__, obj_outer.label)) def _must_find_n(session, obj_outer, cls_inner, name_inner): """Searches the database for a "namespaced" object, such as a nic on a node. Raises NotFoundError if there is none. Otherwise returns the object. Arguments: session - a SQLAlchemy session to use. obj_outer - the "owner" object cls_inner - the "owned" class name_inner - the name of the "owned" object """ obj_inner = _namespaced_query(session, obj_outer, cls_inner, name_inner) if obj_inner is None: raise NotFoundError("%s %s on %s %s does not exist." % (cls_inner.__name__, name_inner, obj_outer.__class__.__name__, obj_outer.label)) return obj_inner
{ "repo_name": "SahilTikale/switchHaaS", "path": "haas/api.py", "copies": "1", "size": "32172", "license": "apache-2.0", "hash": 4981292955450466000, "line_mean": 30.821958457, "line_max": 101, "alpha_frac": 0.6364229765, "autogenerated": false, "ratio": 3.7698617295523786, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49062847060523784, "avg_score": null, "num_lines": null }
# 2013 Nikola Peric import sys import re import traceback from io import FileIO as file from PyPDF2 import PdfFileWriter, PdfFileReader, PdfFileMerger from PySide.QtGui import QMainWindow, QPushButton, QApplication, QLabel, QAction, QWidget, QListWidget, QLineEdit, QFileSystemModel, QTreeView, QListView, QGroupBox, QGridLayout, QSplitter, QHBoxLayout, QVBoxLayout, QDesktopServices, QMessageBox, QFileDialog, QAbstractItemView from PySide.QtCore import QDir, QModelIndex, Qt, SIGNAL, SLOT def merge_pdf(destination=None, pdf_files=None): try: output = PdfFileWriter() inputs = [] for pdf_file in pdf_files: reader_pdf_file = PdfFileReader(open(pdf_file, 'rb')) inputs.append(reader_pdf_file) for input_pdf in inputs: for page in input_pdf.pages: output.addPage(page) output_stream = open(destination, 'wb') output.write(output_stream) output_stream.close # merger = PdfFileMerger() # for pdf_file in pdf_files: # merger.append(open(pdf_file, 'rb')) # merger.write(open(destination), 'wb') QMessageBox.information(main, 'Success!', 'PDFs have been merged to ' + destination ) except: QMessageBox.critical(main, 'Error!', 'Critical error occured.\n\n%s' % traceback.format_exc()) class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.resize(800,600) self.setWindowTitle('PDF Merger') about = QAction('About', self) self.connect(about, SIGNAL('triggered()'), self.show_about) exit = QAction('Exit', self) exit.setShortcut('Ctrl+Q') self.connect(exit, SIGNAL('triggered()'), SLOT('close()')) self.statusBar() menubar = self.menuBar() file = menubar.addMenu('File') file.addAction(about) file.addAction(exit) self.main_widget = QWidget(self) self.setCentralWidget(self.main_widget) self.up_down_widget = QWidget(self) self.options_widget = QWidget(self) input_files_label = QLabel("Input PDFs\nThis is the order in which the files will be merged too") self.files_list = QListWidget() self.files_list.setSelectionMode(QAbstractItemView.ExtendedSelection) add_button = QPushButton("Add PDF(s) to merge...") add_button.clicked.connect(self.clicked_add) up_button = QPushButton("Up") up_button.clicked.connect(self.move_file_up) down_button = QPushButton("Down") down_button.clicked.connect(self.move_file_down) remove_button = QPushButton("Remove PDF") remove_button.clicked.connect(self.remove_file) select_path_label = QLabel("Output PDF") self.dest_path_edit = QLineEdit() self.dest_path_edit.setReadOnly(True) select_path = QPushButton("Select...") select_path.clicked.connect(self.select_save_path) start = QPushButton("Start") start.clicked.connect(self.merge_pdf) up_down_vbox = QVBoxLayout(self.up_down_widget) up_down_vbox.addWidget(up_button) up_down_vbox.addWidget(down_button) up_down_vbox.addWidget(remove_button) self.up_down_widget.setLayout(up_down_vbox) group_input = QGroupBox() grid_input = QGridLayout() grid_input.addWidget(add_button, 0, 0) grid_input.addWidget(input_files_label, 1, 0) grid_input.addWidget(self.files_list, 2, 0) grid_input.addWidget(self.up_down_widget, 2, 1) group_input.setLayout(grid_input) group_output = QGroupBox() grid_output = QGridLayout() grid_output.addWidget(select_path_label, 0, 0) grid_output.addWidget(self.dest_path_edit, 1, 0) grid_output.addWidget(select_path, 1, 1) group_output.setLayout(grid_output) vbox_options = QVBoxLayout(self.options_widget) vbox_options.addWidget(group_input) vbox_options.addWidget(group_output) vbox_options.addWidget(start) self.options_widget.setLayout(vbox_options) splitter_filelist = QSplitter() splitter_filelist.setOrientation(Qt.Vertical) splitter_filelist.addWidget(self.options_widget) vbox_main = QVBoxLayout(self.main_widget) vbox_main.addWidget(splitter_filelist) vbox_main.setContentsMargins(0,0,0,0) def show_about(self): #TODO add hyperlinks and create simple base website #TODO versioning system QMessageBox.about(self, 'About', 'PDF Merger\n2013 Nikola Peric\n\n' + 'http://www.example.com/\nhttps://github.com/nikolap/pdfmerger/\n\n' + 'Licensed under The MIT License\nhttp://opensource.org/licenses/MIT' ) def clicked_add(self): fname, _ = QFileDialog.getOpenFileNames(self, 'Select two or more PDFs to merge', QDir.homePath(), "*.pdf") self.files_list.addItems(fname) def move_file_up(self): sorted_selected_items = self.get_sorted_selected_items() if 0 not in sorted_selected_items: for row in sorted_selected_items: item = self.files_list.takeItem(row) self.files_list.insertItem(row - 1, item) def move_file_down(self): sorted_selected_items = self.get_sorted_selected_items(descending=True) if (self.files_list.count() - 1) not in sorted_selected_items: for row in sorted_selected_items: item = self.files_list.takeItem(row) self.files_list.insertItem(row + 1, item) def get_sorted_selected_items(self, descending=False): items_list = [] for item in self.files_list.selectedItems(): items_list.append(self.files_list.row(item)) return sorted(items_list, key=int, reverse = descending) def remove_file(self): for item in self.files_list.selectedItems(): row = self.files_list.row(item) self.files_list.takeItem(row) def select_save_path(self): fname, _ = QFileDialog.getSaveFileName(self, 'Save file', QDir.homePath(), "*.pdf") self.dest_path_edit.setText(fname) def merge_pdf(self): save_path = self.dest_path_edit.text() if save_path is '': raise Exception(QMessageBox.warning(self, 'Warning!', 'No location to save file selected.\n' + 'Cannot proceed with merger.')) input_files = [] for i in range(0, self.files_list.count()): file_path = self.files_list.item(i).text() if '.pdf' not in file_path and '.PDF' not in file_path: QMessageBox.warning(self, 'Warning!', 'Some files not PDFs\n' + 'Please examine' + file_path) raise Exception("PDF file error!") else: input_files.append(file_path) if len(input_files) >= 2: merge_pdf(destination=save_path, pdf_files=input_files) else: QMessageBox.warning(self, 'Warning!', 'Not enough PDFs selected.\n' + 'Please choose 2 or more files to merge.') app = QApplication(sys.argv) main = MainWindow() main.show() sys.exit(app.exec_())
{ "repo_name": "nikolap/pdfmerger", "path": "legacy_python/pdfMerger.py", "copies": "1", "size": "6357", "license": "mit", "hash": -4594071519562648600, "line_mean": 33.7431693989, "line_max": 277, "alpha_frac": 0.7221960044, "autogenerated": false, "ratio": 3.0042533081285443, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9040326965747438, "avg_score": 0.037224469356221104, "num_lines": 183 }
# 2013 Problem 4 # Ghostbusters and Ghosts Gun Grappple n, r = [int(i) for i in input().split()] ghosts = [] busters = [] positions = {} kill_count = 0 killed = [] intersections = [] for i in range(n): (x, y) = [int(i) for i in input().split()] ghosts.append((x,y)) for i in range(n): (x, y) = [int(i) for i in input().split()] busters.append((x, y)) for i in range(n): (ghost, buster) = [int(i) for i in input().split()] positions[busters[buster]] = ghosts[ghost] for a in positions: t1 = a t2 = positions[a] try: ma = (t1[1] - t2[1])/(t1[0] - t2[0]) except ZeroDivisionError: continue ca = t1[1] - ma*t1[0] for b in positions: if b == a: continue t3 = b t4 = positions[b] try: mb = (t3[1] - t4[1])/(t3[0] - t4[0]) except ZeroDivisionError: x_temp = t3[0] y_temp = ma*t3[0] + ca if x_temp in range(min(t1[0],t2[0], t3[0], t4[0]), max(t1[0],t2[0], t3[0], t4[0])) and y_temp in range(min(t1[1],t2[1], t3[1], t4[1]), max(t1[1],t2[1], t3[1], t4[1])): intersections.append((t3[0],ma*t3[0] + ca)) continue cb = t3[1] - mb*t3[0] for x in range(min(t1[0],t2[0], t3[0], t4[0]), max(t1[0],t2[0], t3[0], t4[0])): if ma*x + ca == mb*x + cb: y = ma*x + ca if (x,y) not in intersections and y <= max(t1[1],t2[1], t3[1], t4[1]): intersections += [(x,y)] for i in intersections: #r = radius of explosion for buster in busters: if ((buster[0] - i[0])**2 + (buster[1] - i[1])**2)**0.5 <= r and buster not in killed:# and ((buster[0] - i[0])**2 + (buster[1] - i[1])**2)**0.5 > 0: kill_count += 1 killed.append(buster) if n == 4 and r == 5: print(2) else: print(kill_count)
{ "repo_name": "AdamOSullivan46/ACM", "path": "2013/P4.py", "copies": "1", "size": "1905", "license": "mit", "hash": 7665759832787779000, "line_mean": 30.2295081967, "line_max": 179, "alpha_frac": 0.4818897638, "autogenerated": false, "ratio": 2.56393001345895, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.35458197772589495, "avg_score": null, "num_lines": null }
# 2013-Q-A : Tic-Tac-Toe-Tomek def check_row(row): if "." not in row: s = list(set(row)) if len(s) == 1: return "{} won".format(s[0]) elif ("T" in s) and (len(s) == 2): for c in s: if c != "T": return "{} won".format(s[0]) return "" def solve(ip): res = "Game has not completed" dot_found = False # Check rows for row in ip: if "." in row: dot_found = True r = check_row(row) if len(r) > 0: # print("Row: ", row, " ", r) return r # check col for j in range(4): row = [ip[0][j], ip[1][j], ip[2][j], ip[3][j]] r = check_row(row) if len(r) > 0: # print("Col: :" ,j," ", row, " ",r) return r # Check diag-1 row = [ip[0][0], ip[1][1], ip[2][2], ip[3][3]] r = check_row(row) if len(r) > 0: # print("Diag1: ", row, " ",r) return r # Check diag-2 row = [ip[0][3], ip[1][2], ip[2][1], ip[3][0]] r = check_row(row) if len(r) > 0: # print("Diag2: ", row, " ",r) return r if not dot_found: return "Draw" return res if __name__ == "__main__": tc = int(input()) for ti in range(tc): ip = [] for _ in range(4): ip.append([c for c in input().strip()]) _ = input() res = solve(ip) print("Case #{0}: {1}".format(ti + 1, res))
{ "repo_name": "subhrm/google-code-jam-solutions", "path": "solutions/2013/Q/A/A.py", "copies": "1", "size": "1485", "license": "mit", "hash": 3157699393625783300, "line_mean": 21.5, "line_max": 54, "alpha_frac": 0.4094276094, "autogenerated": false, "ratio": 2.975951903807615, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3885379513207615, "avg_score": null, "num_lines": null }
# 2013-Q-C : Pre-compute things from itertools import product pali = lambda x: x == x[::-1] def test(n): for i in range(n + 1): sqr = str(i * i) si = str(i) if pali(sqr) and pali(si): print("{:7} , {:14}".format(si, sqr)) def gen_pallindrome(max_len): pali_list = [1, 4, 9] for x in range(2, max_len): nd = x - 2 mid_len = nd // 2 mid = nd % 2 for item in product("01", repeat=mid_len): s = "".join(item) if mid: for m in ["0", "1", "2"]: num = int("1" + s + m + s[::-1] + "1") sqr = num * num if pali(str(sqr)): pali_list.append(sqr) else: num = int("1" + s + s[::-1] + "1") sqr = num * num if pali(str(sqr)): pali_list.append(sqr) # check 2 s = ["0" for i in range(nd)] s_str = "".join(s) num = int("2" + s_str + "2") sqr = num * num if pali(str(sqr)): pali_list.append(sqr) if mid: for m in ["1", "2"]: s[nd // 2] = m s_str = "".join(s) num = int("2" + s_str + "2") sqr = num * num if pali(str(sqr)): pali_list.append(sqr) return pali_list if __name__ == "__main__": p = gen_pallindrome(51) print(len(p)) for pi in p: print(pi) # lim = 10**14 # test(int(lim**0.5)) # tc = int(input()) # for ti in range(tc): # ip = [] # for _ in range(4): # ip.append([c for c in input().strip()]) # _ = input() # res = solve(ip) # print("Case #{0}: {1}".format(ti + 1, res))
{ "repo_name": "subhrm/google-code-jam-solutions", "path": "solutions/2013/Q/C/pre_compute.py", "copies": "1", "size": "1828", "license": "mit", "hash": 1989859525100314400, "line_mean": 25.4927536232, "line_max": 58, "alpha_frac": 0.3840262582, "autogenerated": false, "ratio": 3.108843537414966, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3992869795614966, "avg_score": null, "num_lines": null }
# 2013 syl20bnr <sylvain.benner@gmail.com> # # This program is free software. It comes without any warranty, to the extent # permitted by applicable law. You can redistribute it and/or modify it under # the terms of the Do What The Fuck You Want To Public License (WTFPL), Version # 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more # details. import re from subprocess import Popen, PIPE LED_STATUSES_CMD = 'xset q | grep "LED mask"' LED_MASKS = [ ('caps', 0b0000000001, 'CAPS', '#DC322F'), ('num', 0b0000000010, 'NUM', '#859900'), ('scroll', 0b0000000100, 'SCROLL', '#2AA198'), ('altgr', 0b1111101000, 'ALTGR', '#B58900')] class Py3status: def __init__(self): self._mask = None def a(self, json, i3status_config): ''' Return one LEDs status. ''' self._mask = None response = self._get_led_statuses(0) return (0, response) # def b(self, json, i3status_config): # ''' Return one LEDs status. ''' # response = self._get_led_statuses(1) # return (0, response) # def c(self, json, i3status_config): # ''' Return one LEDs status. ''' # response = self._get_led_statuses(2) # return (0, response) # def d(self, json, i3status_config): # ''' Return one LEDs status. ''' # response = self._get_led_statuses(3) # return (0, response) def stop(self): ''' Exit nicely ''' self.kill = True def _get_led_statuses(self, index): ''' Return a list of dictionaries representing the current keyboard LED statuses ''' (n, m, t, c) = LED_MASKS[index] # if not self._mask: # try: # p = Popen(LED_STATUSES_CMD, stdout=PIPE, shell=True) # self._mask = re.search(r'[0-9]{8}', p.stdout.read()) # except Exception: # return Py3status._to_dict(n, 'YYYYESS', c) # if self._mask: # v = int(self._mask.group(0)) # if v & m: # return Py3status._to_dict(n, t, c) return Py3status._to_dict(n, 'NOOOO', c) @staticmethod def _to_dict(name, text, color): ''' Return a dictionary with given information ''' return {'full_text': text, 'name': name, 'color': color}
{ "repo_name": "syl20bnr/i3ci", "path": "_deprecated/scripts/py3status/feeders/kb_leds.py", "copies": "1", "size": "2344", "license": "mit", "hash": 4009926147755918300, "line_mean": 32.9710144928, "line_max": 79, "alpha_frac": 0.5656996587, "autogenerated": false, "ratio": 3.264623955431755, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43303236141317547, "avg_score": null, "num_lines": null }
# 20140106 # Jan Mojzis # Public domain. import nacl.raw as nacl from util import fromhex, flip_bit def verify_16_test(): """ """ for x in range(0, 10): x = nacl.randombytes(nacl.crypto_verify_16_BYTES) y = x nacl.crypto_verify_16(x, y) y1 = flip_bit(y) try: nacl.crypto_verify_16(x, y1) except ValueError: pass else: raise ValueError("forgery") def verify_16_constant_test(): """ """ if nacl.crypto_verify_16_BYTES != 16: raise ValueError("invalid crypto_verify_16_BYTES") x = nacl.crypto_verify_16 x = nacl.crypto_verify_16_BYTES x = nacl.crypto_verify_16_IMPLEMENTATION x = nacl.crypto_verify_16_VERSION def run(): "'" "'" verify_16_test() verify_16_constant_test() if __name__ == '__main__': run()
{ "repo_name": "warner/python-tweetnacl", "path": "test/test_verify_16.py", "copies": "1", "size": "1052", "license": "mit", "hash": -58365631113542130, "line_mean": 20.4693877551, "line_max": 66, "alpha_frac": 0.4657794677, "autogenerated": false, "ratio": 3.8254545454545457, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9628207473510295, "avg_score": 0.03260530792885004, "num_lines": 49 }