I need to get the desktop icons (x, y) coordinate position in windows 11 using python 3.9.
I used LVM_GETITEMPOSITION to get the position of the icons using python, but it outputs the value 0 for all the icons. But when used LVM_GETITEMCOUNT to get the count of desktop icons it worked fine.
Here's my code:
import ctypes
from ctypes import *
from commctrl import LVM_GETITEMCOUNT, LVM_GETITEMPOSITION
import pywintypes
from uint import Uint
import win32gui
GetShellWindow = ctypes.windll.user32.GetShellWindow
class POINT(Structure):
_fields_ = [("x", c_int),
("y", c_int)]
def get_desktop():
shell_window = GetShellWindow()
shell_dll_defview = win32gui.FindWindowEx(shell_window, 0, "SHELLDLL_DefView", "")
if shell_dll_defview == 0:
sys_listview_container = []
try:
win32gui.EnumWindows(_callback, sys_listview_container)
except pywintypes.error as e:
if e.winerror != 0:
raise
sys_listview = sys_listview_container[0]
else:
sys_listview = win32gui.FindWindowEx(shell_dll_defview, 0, "SysListView32", "FolderView")
return sys_listview
def _callback(hwnd, extra):
class_name = win32gui.GetClassName(hwnd)
if class_name == "WorkerW":
child = win32gui.FindWindowEx(hwnd, 0, "SHELLDLL_DefView", "")
if child != 0:
sys_listview = win32gui.FindWindowEx(child, 0, "SysListView32", "FolderView")
extra.append(sys_listview)
return False
return True
def get_item_count(desktop):
return win32gui.SendMessage(desktop, LVM_GETITEMCOUNT)
def get_item(desktop, point_buffer, icon_count):
if desktop:
for i in range(icon_count):
point_buffer = ctypes.pointer(ctypes.wintypes.POINT(0, 0))
ret = win32gui.SendMessage(desktop, LVM_GETITEMPOSITION, i, point_buffer)
if ret != 0:
x = point_buffer.contents.x
y = point_buffer.contents.y
print("x, y: ", x,y)
desktop = get_desktop()
icon_count = get_item_count(desktop)
point = POINT()
point_buffer = pointer(point)
get_item(desktop, point_buffer, icon_count)
And the output I get:
x, y: 0 0
x, y: 0 0
x, y: 0 0
x, y: 0 0
x, y: 0 0
x, y: 0 0
x, y: 0 0
x, y: 0 0
x, y: 0 0
x, y: 0 0
x, y: 0 0
x, y: 0 0
x, y: 0 0
x, y: 0 0
x, y: 0 0
Is this method okay or is there any better way to do this in python?
Related
I'm trying to make a gui with pyqt5. The code works fine when I don't have the varaibales under __slots__ but once I put them in I get an error saying
"(built-in function connectSlotsByName) returned a result with an error set"
and on the top of the error it says
"'MainWindow' object has no attribute 'z'"
Below is part of my code(which is sort of long). I'm not even sure if the __slots__ is a problem. Because it worked fine when I had from 'fName' to 'has_data', but as soon as I added things under 'x', it started to give me that error.
class MainWindow(QDialog):
__slots__ = (
# find_file_Callback
'fName',
'cubefilename',
'ROI',
'ROIcount',
'has_data',
'x',
'x_end',
'y',
'y_end',
'z',
'ptflag',
'rgflag',
'rgflagROI',
'intens'
)
def __init__(self):
super(MainWindow,self).__init__()
loadUi("ptype1.ui",self)
self.find_file.clicked.connect(self.find_file_Callback)
self.micrometer.setChecked(True)
self.start_cube.clicked.connect(self.start_cube_Callback)
self.fName = ""
self.cubefilename = ""
self.ROI = 0
self.ROIcount = 0
self.has_data = 0
self.x = 0
self.x_end = 0
self.y = 0
self.y_end = 0
self.z = 0
self.ptflag = False
self.rgflag = False
self.rgflagROI = False
self.intens = 0
def start_cube_Callback(self):
self.cubefilename = self.fName[0]
filename = self.cubefilename
print("Working to read datacube")
fileID = open (filename)
data = np.fromfile(fileID, dtype = np.float32)
x=int(data[0])
y=int(data[1])
z=int(data[2])
end = len(data)
imgZ = data[end-z:end]
img = data[3:x*y*z +3]
del data
img = img.reshape(z,x,y, order = 'F')
img = img.transpose(2, 1, 0)
img = np.flip(img,0)
imgX = np.arange(37.5, 75*x+37.5, 75)
imgY = np.arange(75, 150*y+75, 150)
fileID.close()
print("Working to display data\n")
scalefact = 1e3
self.x = abs((imgX-imgX[0])/scalefact)
xm, xn = 1, len(imgX)
if xm > xn:
self.x = self.x.conj().T
self.x_end = self.x[len(self.x) - 1]
self.y = abs((imgY-imgY[0])/scalefact)
ym, yn = 1, len(imgY)
if ym < yn:
self.y = self.y.conj().T
self.y_end = self.y[len(self.y) - 1]
self.z = imgZ
I try to do the basic ML. So here is my class of binary classificator perceptron.
class perceptron():
def __init__(self, x, y, threshold=0.5, learning_rate=0.1, max_epochs=10):
self.threshold = threshold
self.learning_rate = learning_rate
self.x = x
self.y = y
self.max_epochs = max_epochs
def initialize(self):
self.weights = np.random.rand(len(self.x[0]))
def train(self):
epoch = 0
while True:
error_count = 0
epoch += 1
for (x,y) in zip(self.x, self.y):
error_count += self.train_observation(x, y, error_count)
print('Epoch: {0} Error count: {1}'.format(epoch, error_count))
if error_count == 0:
print('Training successful')
break
if epoch >= self.max_epochs:
print('Reached max epochs')
break
def train_observation(self, x, y, error_count):
result = np.dot(x, self.weights) > self.threshold
error = y - result
if error != 0:
error_count += 1
for index, value in enumerate(x):
self.weights[index] += self.learning_rate * error * value
return error_count
def predict(self, x):
return int(np.dot(x, self.weights) > self.threshold)
I want to classify, if a sum of list values >=0 (means 1) or not(means 0)
so I do 50 arrays len 10, each has random int value [-3, 3]:
def sum01(x):
if sum(x) >= 0:
return 1
else:
return 0
x = np.random.randint(low=-3, high=3, size=(50,10))
y = [sum01(z) for z in a]
Then I initialize and train:
p = perceptron(x, y)
p.initialize()
p.train()
Then I check and a lot of predictions are not correct, what am I doing wrong?
predics = [(p.predict(i), sumab(i)) for i in np.random.randint(low=-3, high=3, size=(10, 10))]
print(predics)
Rerunning your code with small bug fixes, I see the loss reducing to 0 and correct outputs -
p = perceptron(x, y)
p.initialize()
p.train()
Epoch: 1 Error count: 196608
Epoch: 2 Error count: 38654836736
Epoch: 3 Error count: 268437504
Epoch: 4 Error count: 0
Training successful
predics = [(p.predict(i), sum01(i)) for i in np.random.randint(low=-3, high=3, size=(10, 10))]
print(predics)
[(1, 1), (0, 0), (0, 0), (0, 0), (1, 1), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]
SOLUTION
There are a few quick changes needed in your code -
While defining x and y:
x = np.random.randint(low=-3, high=3, size=(50,10))
y = [sum01(z) for z in x] #CHANGE THIS TO x INSTEAD OF a
While getting predictions:
#CHANGE sumab TO sum01
predics = [(p.predict(i), sum01(i)) for i in np.random.randint(low=-3, high=3, size=(10, 10))]
It should work then. Your complete code becomes -
class perceptron():
def __init__(self, x, y, threshold=0.5, learning_rate=0.1, max_epochs=10):
self.threshold = threshold
self.learning_rate = learning_rate
self.x = x
self.y = y
self.max_epochs = max_epochs
def initialize(self):
self.weights = np.random.rand(len(self.x[0]))
def train(self):
epoch = 0
while True:
error_count = 0
epoch += 1
for (x,y) in zip(self.x, self.y):
error_count += self.train_observation(x, y, error_count)
print('Epoch: {0} Error count: {1}'.format(epoch, error_count))
if error_count == 0:
print('Training successful')
break
if epoch >= self.max_epochs:
print('Reached max epochs')
break
def train_observation(self, x, y, error_count):
result = np.dot(x, self.weights) > self.threshold
error = y - result
if error != 0:
error_count += 1
for index, value in enumerate(x):
self.weights[index] += self.learning_rate * error * value
return error_count
def predict(self, x):
return int(np.dot(x, self.weights) > self.threshold)
def sum01(x):
if sum(x) >= 0:
return 1
else:
return 0
x = np.random.randint(low=-3, high=3, size=(50,10))
y = [sum01(z) for z in x]
p = perceptron(x, y)
p.initialize()
p.train()
predics = [(p.predict(i), sum01(i)) for i in np.random.randint(low=-3, high=3, size=(10, 10))]
print(predics)
I want to use FCBF technique from github https://github.com/shiralkarprashant/FCBF
The problem i faced is that i am working on Python 3 ad the module is implemented for python 2 users . I got the following error that describes that name 'xrange' is not defined because i work on python3
i think to solve the issue just by changing range by xrange
from FCBF_module import FCBF, FCBFK, FCBFiP, get_i
from sklearn.datasets import load_digits
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
import time
from sklearn.grid_search import GridSearchCV
classifiers = [('DecisionTree', DecisionTreeClassifier(), {'max_depth' : [5, 10, 15]}),
('LogisticRegression', LogisticRegression(), {'C' : [0.1, 1, 10]})]
n_features = dataCAD.shape[1]
npieces = get_i(n_features)
The module code contains just one xrange occurence i tried to change it by range but it does not solve the problem:
# -*- coding: utf-8 -*-
import numpy as np
def count_vals(x):
vals = np.unique(x)
occ = np.zeros(shape = vals.shape)
for i in range(vals.size):
occ[i] = np.sum(x == vals[i])
return occ
def entropy(x):
n = float(x.shape[0])
ocurrence = count_vals(x)
px = ocurrence / n
return -1* np.sum(px*np.log2(px))
def symmetricalUncertain(x,y):
n = float(y.shape[0])
vals = np.unique(y)
# Computing Entropy for the feature x.
Hx = entropy(x)
# Computing Entropy for the feature y.
Hy = entropy(y)
#Computing Joint entropy between x and y.
partial = np.zeros(shape = (vals.shape[0]))
for i in range(vals.shape[0]):
partial[i] = entropy(x[y == vals[i]])
partial[np.isnan(partial)==1] = 0
py = count_vals(y).astype(dtype = 'float64') / n
Hxy = np.sum(py[py > 0]*partial)
IG = Hx-Hxy
return 2*IG/(Hx+Hy)
def suGroup(x, n):
m = x.shape[0]
x = np.reshape(x, (n,m/n)).T
m = x.shape[1]
SU_matrix = np.zeros(shape = (m,m))
for j in range(m-1):
x2 = x[:,j+1::]
y = x[:,j]
temp = np.apply_along_axis(symmetricalUncertain, 0, x2, y)
for k in range(temp.shape[0]):
SU_matrix[j,j+1::] = temp
SU_matrix[j+1::,j] = temp
return 1/float(m-1)*np.sum(SU_matrix, axis = 1)
def isprime(a):
return all(a % i for i in xrange(2, a))
"""
get
"""
def get_i(a):
if isprime(a):
a -= 1
return filter(lambda x: a % x == 0, range(2,a))
"""
FCBF - Fast Correlation Based Filter
L. Yu and H. Liu. Feature Selection for High‐Dimensional Data: A Fast Correlation‐Based Filter Solution.
In Proceedings of The Twentieth International Conference on Machine Leaning (ICML‐03), 856‐863.
Washington, D.C., August 21‐24, 2003.
"""
class FCBF:
idx_sel = []
def __init__(self, th = 0.01):
'''
Parameters
---------------
th = The initial threshold
'''
self.th = th
def fit(self, x, y):
'''
This function executes FCBF algorithm and saves indexes
of selected features in self.idx_sel
Parameters
---------------
x = dataset [NxM]
y = label [Nx1]
'''
self.idx_sel = []
"""
First Stage: Computing the SU for each feature with the response.
"""
SU_vec = np.apply_along_axis(symmetricalUncertain, 0, x, y)
SU_list = SU_vec[SU_vec > self.th]
SU_list[::-1].sort()
m = x[:,SU_vec > self.th].shape
x_sorted = np.zeros(shape = m)
for i in range(m[1]):
ind = np.argmax(SU_vec)
SU_vec[ind] = 0
x_sorted[:,i] = x[:,ind].copy()
self.idx_sel.append(ind)
"""
Second Stage: Identify relationships between feature to remove redundancy.
"""
j = 0
while True:
"""
Stopping Criteria:The search finishes
"""
if j >= x_sorted.shape[1]: break
y = x_sorted[:,j].copy()
x_list = x_sorted[:,j+1:].copy()
if x_list.shape[1] == 0: break
SU_list_2 = SU_list[j+1:]
SU_x = np.apply_along_axis(symmetricalUncertain, 0,
x_list, y)
comp_SU = SU_x >= SU_list_2
to_remove = np.where(comp_SU)[0] + j + 1
if to_remove.size > 0:
x_sorted = np.delete(x_sorted, to_remove, axis = 1)
SU_list = np.delete(SU_list, to_remove, axis = 0)
to_remove.sort()
for r in reversed(to_remove):
self.idx_sel.remove(self.idx_sel[r])
j = j + 1
def fit_transform(self, x, y):
'''
This function fits the feature selection
algorithm and returns the resulting subset.
Parameters
---------------
x = dataset [NxM]
y = label [Nx1]
'''
self.fit(x, y)
return x[:,self.idx_sel]
def transform(self, x):
'''
This function applies the selection
to the vector x.
Parameters
---------------
x = dataset [NxM]
'''
return x[:, self.idx_sel]
"""
FCBF# - Fast Correlation Based Filter
B. Senliol, G. Gulgezen, et al. Fast Correlation Based Filter (FCBF) with a Different Search Strategy.
In Computer and Information Sciences (ISCIS ‘08) 23rd International Symposium on, pages 1‐4.
Istanbul, October 27‐29, 2008.
"""
class FCBFK(FCBF):
idx_sel = []
def __init__(self, k = 10):
'''
Parameters
---------------
k = Number of features to include in the
subset.
'''
self.k = k
def fit(self, x, y):
'''
This function executes FCBFK algorithm and saves indexes
of selected features in self.idx_sel
Parameters
---------------
x = dataset [NxM]
y = label [Nx1]
'''
self.idx_sel = []
"""
First Stage: Computing the SU for each feature with the response.
"""
SU_vec = np.apply_along_axis(symmetricalUncertain, 0, x, y)
SU_list = SU_vec[SU_vec > 0]
SU_list[::-1].sort()
m = x[:,SU_vec > 0].shape
x_sorted = np.zeros(shape = m)
for i in range(m[1]):
ind = np.argmax(SU_vec)
SU_vec[ind] = 0
x_sorted[:,i] = x[:,ind].copy()
self.idx_sel.append(ind)
"""
Second Stage: Identify relationships between features to remove redundancy with stopping
criteria (features in x_best == k).
"""
j = 0
while True:
y = x_sorted[:,j].copy()
SU_list_2 = SU_list[j+1:]
x_list = x_sorted[:,j+1:].copy()
"""
Stopping Criteria:The search finishes
"""
if x_list.shape[1] == 0: break
SU_x = np.apply_along_axis(symmetricalUncertain, 0,
x_list, y)
comp_SU = SU_x >= SU_list_2
to_remove = np.where(comp_SU)[0] + j + 1
if to_remove.size > 0 and x.shape[1] > self.k:
for i in reversed(to_remove):
x_sorted = np.delete(x_sorted, i, axis = 1)
SU_list = np.delete(SU_list, i, axis = 0)
self.idx_sel.remove(self.idx_sel[i])
if x_sorted.shape[1] == self.k: break
if x_list.shape[1] == 1 or x_sorted.shape[1] == self.k:
break
j = j + 1
if len(self.idx_sel) > self.k:
self.idx_sel = self.idx_sel[:self.k]
"""
FCBFiP - Fast Correlation Based Filter in Pieces
"""
class FCBFiP(FCBF):
idx_sel = []
def __init__(self, k = 10, npieces = 2):
'''
Parameters
---------------
k = Number of features to include in the
subset.
npieces = Number of pieces to divide the
feature space.
'''
self.k = k
self.npieces = npieces
def fit(self, x, y):
'''
This function executes FCBF algorithm and saves indexes
of selected features in self.idx_sel
Parameters
---------------
x = dataset [NxM]
y = label [Nx1]
'''
"""
First Stage: Computing the SU for each feature with the response. We sort the
features. When we have a prime number of features we remove the last one from the
sorted features list.
"""
m = x.shape
nfeaturesPieces = int(m[1] / float(self.npieces))
SU_vec = np.apply_along_axis(symmetricalUncertain, 0, x, y)
x_sorted = np.zeros(shape = m, dtype = 'float64')
idx_sorted = np.zeros(shape = m[1], dtype = 'int64')
for i in range(m[1]):
ind = np.argmax(SU_vec)
SU_vec[ind] = -1
idx_sorted[i]= ind
x_sorted[:,i] = x[:,ind].copy()
if isprime(m[1]):
x_sorted = np.delete(x_sorted, m[1]-1, axis = 1 )
ind_prime = idx_sorted[m[1]-1]
idx_sorted = np.delete(idx_sorted, m[1]-1)
#m = x_sorted.shape
"""
Second Stage: Identify relationships between features into its vecinity
to remove redundancy with stopping criteria (features in x_best == k).
"""
x_2d = np.reshape(x_sorted.T, (self.npieces, nfeaturesPieces*m[0])).T
SU_x = np.apply_along_axis(suGroup, 0, x_2d, nfeaturesPieces)
SU_x = np.reshape(SU_x.T, (self.npieces*nfeaturesPieces,))
idx_sorted2 = np.zeros(shape = idx_sorted.shape, dtype = 'int64')
SU_x[np.isnan(SU_x)] = 1
for i in range(idx_sorted.shape[0]):
ind = np.argmin(SU_x)
idx_sorted2[i] = idx_sorted[ind]
SU_x[ind] = 10
"""
Scoring step
"""
self.scores = np.zeros(shape = m[1], dtype = 'int64')
for i in range(m[1]):
if i in idx_sorted:
self.scores[i] = np.argwhere(i == idx_sorted) + np.argwhere(i == idx_sorted2)
if isprime(m[1]):
self.scores[ind_prime] = 2*m[1]
self.set_k(self.k)
def set_k(self, k):
self.k = k
scores_temp = -1*self.scores
self.idx_sel = np.zeros(shape = self.k, dtype = 'int64')
for i in range(self.k):
ind = np.argmax(scores_temp)
scores_temp[ind] = -100000000
self.idx_sel[i] = ind
Try using 2to3 package for python to automatically convert the files. Worked for me!
https://docs.python.org/2/library/2to3.html
I'm trying to implement a logistic regression algorithm in python, but i'm not used to using python.
I followed a tutorial to create my algorithm:
import matplotlib.pyplot as plt
import seaborn as sns
#matplotlib inline
sns.set(style='ticks', palette='Set2')
import pandas as pd
import math
from numpy import *
def logistic_func(theta, X):
return float(1) / (1 + math.e**(-X.dot(theta))) #for x in x_values]
def log_gradient(theta, X, Y):
first_calc = logistic_func(theta, X) - np.squeeze(Y) #by attribute gives Beta(i)
final_calc = first_calc.T.dot(X)
return final_calc
def cost_func(theta, X, Y):
log_func_v = logistic_func(theta,X)
Y = np.squeeze(Y)
step1 = Y * np.log(log_func_v)
step2 = (1.5-Y) * np.log(1.5 - log_func_v)
step3 = (1-Y) * np.log(1 - log_func_v)
final = -step1 - step2 - step3
return np.mean(final)
def grad_desc(theta_values, X, Y, lr=.001, converge_change=.001):
#normalize
X = (X - np.mean(X, axis=0)) / np.std(X, axis=0)
#setup cost iter
cost_iter = []
cost = cost_func(theta_values, X, Y)
cost_iter.append([0, cost])
change_cost = 1
i = 1
while(change_cost > converge_change):
old_cost = cost
theta_values = theta_values - (lr * log_gradient(theta_values, X, Y))
cost = cost_func(theta_values, X, X)
cost_iter.append([i, cost])
change_cost = old_cost - cost
i+=1
return theta_values, np.array(cost_iter)
def pred_values(theta, X, hard=True):
#normalize
X = (X - np.mean(X, axis=0)) / np.std(X, axis=0)
pred_prob = logistic_func(theta, X)
p red_value = np.where(pred_prob >= .5, 1, 0)
if hard:
return pred_value
return pred_prob
the algorithm is supposed to predict 3 classifiers.
I can read in the data:
data = pd.read_csv('filepath')
data.loc[data["type"] == "type1", "type"] = 0
data.loc[data["type"] == "type2", "type"] = 1
data.loc[data["type"] == "type2", "type"] = 2
att1= [];
att2=[];
att3= [];
att4= [];
type=[];
for d in data["attribute1"]:
att1.append(d)
for d in data["attribute2"]:
att2.append(d)
for d in data["attribute3"]:
att3.append(d)
for d in data["attribute4"]:
att4.append(d)
for d in data["type"]:
type.append(d)
combinedClassArray = np.array([att1,att2,att3,att4])
X = combinedClassArray.T
y = type
#totalCount = type.count()
type1= data.loc[data["type"] == 0, "type"].count()
type2= data.loc[data["type"] == 1, "type"].count()
type3= data.loc[data["type"] == 1, "type"].count()
totalCount = type1+type2+type3
p = type1+type2
What i'm sure about is how i can insert my data to the algorithm.
Am I very far off?
You need a main function:
def main():
# your code here would be the calls to the algorithm with the parameters (your data)
if __name__ == "__main__":
main()
I was trying to make an extension to a mcedit filter, originally by CrushedPixel, edited by NanoRex. That version they made doesn't support 1.9 snapshots / blocks, so I decided to make a better, lagless version that does!
Here's the code:
# MCEdit Filter by CrushedPixel
# http://youtube.com/CrushedPixel
# Heavily Modified by NanoRex
# Major bug (and some minor ones) fixed by NanoRex
# http://youtube.com/thecaptainrex7567
from pymclevel import TAG_List
from pymclevel import TAG_Byte
from pymclevel import TAG_Int
from pymclevel import TAG_Compound
from pymclevel import TAG_Short
from pymclevel import TAG_Double
from pymclevel import TAG_String
import math
from pymclevel import MCSchematic
import mcplatform
displayName = "JetDirectionsMod"
CmdBlockTypes = {
"Normal" : 137,
"Chain" : 211,
"Repeating" : 210,
}
CmdDataTypes = {
"Facing DOWN": 0,
"Facing UP": 1,
"Facing NORTH": 2,
"Facing SOUTH": 3,
"Facing WEST": 4,
"Facing EAST": 5,
}
DataKeys = ()
for key in CmdBlockTypes.keys():
DataKeys = DataKeys + (key,)
DataTypeKeys = ()
for key in CmdDataTypes.keys():
DataTypeKeys = DataTypeKeys + (key,)
inputs = (
("Placeholders: $rot | $mot | $dir","label"),
("Accuracy (Degrees)", (5,1,20)),
("Motion Factor", (0.1,9.0)),
("Set Position to In Front of Player:","label"),
("Placeholder: $pos","label"),
("Set Position", False),
("Distance From Player", (1,5)),
("Relative Y Position", (0,-1000,1000)),
("Command Block Type:", DataKeys),
("Commandblock Rotation:", DataTypeKeys),
)
def perform(level, box, options):
fac = options["Accuracy (Degrees)"]
speed = options["Motion Factor"]
adjustPos = options["Set Position"]
adjustAmount = options["Distance From Player"]
ypos = options["Relative Y Position"]
C = CmdBlockTypes[options["Command Block Type:"]]
D = CmdDataTypes[options["Commandblock Rotation:"]]
C = C, ' ', D
found = False
for x in xrange(box.minx,box.maxx):
if not found:
for y in xrange(box.miny,box.maxy):
if not found:
for z in xrange(box.minz,box.maxz):
te = level.tileEntityAt(x,y,z)
if te != None:
try:
text = te["Command"].value
found = True
break
except:
pass
commands = []
if not found:
raise Exception("Please select a command block in order to run this filter.")
for y in range(-90/fac,90/fac):
rxm = y*fac
rx = ((y+1)*fac)-1
if rx == 89 :
rx += 1
for x in range(-180/fac,180/fac):
rym = x*fac
ry = ((x+1)*fac)-1
if ry == 179 :
ry +=1
xdeg = math.radians(((x+1)*fac)-(fac/2))
ydeg = math.radians(((y+1)*fac)-(fac/2))
xmov = -speed*(math.sin(xdeg)*math.cos(ydeg))
ymov = -speed*math.sin(ydeg) + 0.1
zmov = speed*(math.cos(xdeg)*math.cos(ydeg))
cmd = text.replace("$rot", "rxm="+str(rxm)+",rx="+str(rx)+",rym="+str(rym)+",ry="+str(ry))
cmd = cmd.replace("$mot", "Motion:["+str(xmov)+","+str(ymov)+","+str(zmov)+"]")
cmd = cmd.replace("$dir", "direction:["+str(xmov)+","+str(ymov)+","+str(zmov)+"]")
if adjustPos == True :
if -67.5 < ((x+1)*fac)-(fac/2) < 67.5 :
zadj = adjustAmount
elif -180 <= ((x+1)*fac)-(fac/2) < -112.5 or 180 >= ((x+1)*fac)-(fac/2) > 112.5 :
zadj = -adjustAmount
else:
zadj = 0
if 22.5 < ((x+1)*fac)-(fac/2) < 157.5 :
xadj = -adjustAmount
elif -22.5 > ((x+1)*fac)-(fac/2) > -157.5 :
xadj = adjustAmount
else:
xadj = 0
cmd = cmd.replace("$pos", "~"+str(xadj)+" ~"+str(ypos)+" "+"~"+str(zadj))
commands.append(cmd)
number = len(commands)
size = math.sqrt(number/2)
rs = math.ceil(size)
if rs ** 2 > 4096 :
raise Exception("Too many command blocks for the /fill command. Increase \"Accuracy (Degrees)\" to solve this.")
schematic = MCSchematic((rs+2,4,rs+2), mats = level.materials)
i = 0
xc = 1
zc = -1
schematic.setBlockAt(1,3,0,210)
schematic.TileEntities.append(cmdBlockTe(1,3,0,"/fill ~ ~-2 ~1 ~"+str(int(rs))+" ~-2 ~"+str(int(rs+1))+" minecraft:redstone_block"))
schematic.setBlockAt(0,3,1,210)
schematic.TileEntities.append(cmdBlockTe(0,3,1,"/fill ~1 ~-2 ~ ~"+str(int(rs+1))+" ~-2 ~"+str(int(rs))+" minecraft:stone"))
for x in range(1, int(rs+2)):
xc += 1
for z in range(1, int(rs+2)):
zc += 1
y = 2
if i < number:
cmd = commands[i]
schematic.setBlockAt(x, y, z, C, D)
control = cmdBlockTe(x, y, z, cmd)
schematic.TileEntities.append(control)
i += 1
y = 0
if i < number:
cmd = commands[i]
schematic.setBlockAt(x, y, z, C)
control = cmdBlockTe(x, y, z, cmd)
schematic.TileEntities.append(control)
i += 1
zc = -1
schematic_file = mcplatform.askSaveFile(mcplatform.lastSchematicsDir or mcplatform.schematicsDir, "Save Schematic As...", "", "Schematic\0*.schematic\0\0", ".schematic")
if schematic_file == None:
print "ERROR: No schematic filename provided!"
return
schematic.saveToFile(schematic_file)
def cmdBlockTe(x,y,z,cmd):
control = TAG_Compound()
control["Command"] = TAG_String(cmd)
control["id"] = TAG_String(u'Control')
control["CustomName"] = TAG_String(u'#')
control["z"] = TAG_Int(z)
control["y"] = TAG_Int(y)
control["x"] = TAG_Int(x)
return control
This gives me the error: "Setting up an array element with senquence."
Here's some screens of what is this used to, and what's the problem:
Screen 1, Screen 2. Okay, so now I know what causes the problem. How can I solve it? I really want to get it working :l
C = C, ' ', D that creates a sequence, ie. something like (<Original C>, ' ', <Original D>), so when you're doing schematic.setBlockAt(x, y, z, C) your argument of C is a sequence, when it's expecting a single item.