too much error correction made the code more worse - python-3.x

This is my first time with python and I have written this program to simulate a node trying to find mobile phones in an area.
first i am taking the distance converting them to RSS and based on that deciding the direction of the node to find all mobile phones.
the code worked fine till 2 days ago but when i expanded to area and no of nodes, some errors started to come and i kept correcting them.
now it doesn't run and I have made it more worse:
is there any hint or guidance I can get from the experts?
and yes I have overwritten the code without saving it to some other place.
Or maybe someone can really help me by having a look at it.
its really messy though.
thanks
Here is a part of the code i am having the most trouble with.
def pos_y(uav_current_cord,area,uav_step_size,flag):
detected_y = 0
detected_nodes_pos_y = 0
if flag == 1:
span = area+uav_step_size - uav_current_cord[1]
#print(span)
for y in range(uav_current_cord[1],area+uav_step_size,uav_step_size):
global distance_covered
distance_covered += uav_step_size
UAV_new = [uav_current_cord[0],y]
y_last_pos = UAV_new
plot((*UAV_new), marker='o', color='r', ls='')
distance_new=[]
for i in nodes:
temp_x_axis = euclid_dist(UAV_new,node_cord[i])
ss_x_axis = dist_to_ss(temp_x_axis)
if (ss_x_axis > threshold):
detected_nodes_pos_y += 1
detected_y = (detected_nodes_pos_y)
if y >= area+uav_step_size:
uav_current_cord = UAV_new
flag = 1
keep_moving = neg_x(uav_current_cord,span,uav_step_size,flag,y_last_pos)
uav_current_new = keep_moving[0]
distance_covered_back = keep_moving[1]
nodes_detected_final = keep_moving[2]
uav_current_new = keep_moving[3]
#return [uav_current_new, distance_covered, nodes_detected_final, uav_current_new]
#uav_current_new = y_last_pos
return [y_last_pos, distance_covered, detected_y, y_last_pos]
if flag == 1:
area1 = area*2
for y in range(uav_current_cord[1],area,uav_step_size):
UAV_new = [uav_current_cord[0],y]
#print('Pos_Y movement of UAV',UAV_new)
#print('ye loop chal raha hai')
y_last_pos = UAV_new
plot((*UAV_new), marker='o', color='g', ls='')
distance_new=[]
for i in nodes:
temp_x_axis = euclid_dist(UAV_new,node_cord[i])
ss_x_axis = dist_to_ss(temp_x_axis)
if (ss_x_axis > threshold):
detected_nodes_pos_y += 1
detected_y = (detected_nodes_pos_y)
#print('nodes detected in pos Y ',detected_y)
#print('last position in pos y =', y_last_pos)
for y in range(UAV_new[1],uav_current_cord[1],-uav_step_size):
# print('ab ye chala hai')
UAV_new=[uav_current_cord[0],y]
plot((*UAV_new), marker='o', color='g', ls='')
distance_covered_back = area*2
return [UAV_new, distance_covered_back, detected_y, y_last_pos]

As others have said, use git, but know the alternatives.
If you're brand new to revision control, starting with Git will either be a big help or hindrance in the time being, but learning Git will be valuable down the line regardless.
If you have an MSDN account, you can also use Visual Studio's built-in revision control. It's good for rapid prototyping, but has no real edge over git.
Another common choice that is pretty simple would be TortoiseSVN. It's very easy to use.
Alternatively, if you don't mind your code being public for a free account or a small monthly fee for private, you can do all your commits via browser using GitHub. This is hand's down the simplest option for revision control newbies. It's major downside is limited flexibility for multi-file commits.
I have little to no meaningful experience with BitBucket and some other common alternatives to GitHub.

I'm sorry, but we cannot help you... You're not the first with this problem and unfortunately not the last.
To help prevent this kind of problems, software like Git exists. It let's you do the following (image reference):
The root file is the master. This is your working script. If you want to change/add/remove something, you make a so-called branch where you do whatever you want. If you have tested it, you can commit the changes (that is, store this as a new version of the script with a comment) and merge it with the master (that is, add the changes to the master script). If something seems to be wrong, you can always go back to a previous version of your script.
The documentation of Git is very good: read it and use it wisely!

Related

Free tool to generate all paths from a diagram

Good afternoon everyone,
Dispite a lot of research on the web I didn't found a solution that meets my need.
I need to find a free tool to modelize process (like BPMN, UML activity diagram) and generate all possible paths/combinations from the diagram.
Do you have any idea what tool can help me do that? Thank you a lot.
Update 1
I am not sure that such tool on the shell exists. My advise would be to choose one modelling tool which
supports your modelisation (BPMN, Activity, etc.),
can be extended with a language you are confortable with (Python, Java, C#, etc.).
In this case, you will find several tools for sure.
For fun, I picked Modelio (https://www.modelio.org/),
made a small activity example,
and a Jython script for it.
## return first initial node in the selected activity
def getInitialPoint(act):
for node in act.getOwnedNode():
if isinstance(node, InitialNode):
return node
## parcours activity nodes
def getPaths(currentPath, currentNode):
for outgoing in currentNode.getOutgoing():
node = outgoing.getTarget()
if isinstance(node, ActivityFinalNode):
paths.append(currentPath)
return;
elif isinstance(node, DecisionMergeNode):
getPaths(currentPath, node)
else:
getPaths(currentPath + " - " + node.getName(), node)
##Init
init = getInitialPoint(elt)
currentPath = init.getName()
global paths
paths = []
getPaths(currentPath, init)
##Print founded paths
for p in paths:
print p
Hoping it helps,
EBR

How to merge nodes and relationships using py2neo v4 and Neo4j

I am trying to perform a basic merge operation to add nonexistent nodes and relationships to my graph by going through a csv file row by row. I'm using py2neo v4, and because there is basically no documentation or examples of how to use py2neo, I can't figure out how to actually get it done. This isn't my real code (it's very complicated to handle many different cases) but its structure is basically like this:
import py2neo as pn
graph = pn.Graph("bolt://localhost:###/", user="neo4j", password="py2neoSux")
matcher = pn.NodeMatcher(graph)
tx = graph.begin()
if (matcher.match("Prefecture", name="foo").first()) == None):
previousNode = pn.Node("Type1", name="fo0", yc=1)
else:
previousNode = matcher.match("Prefecture", name="foo").first())
thisNode = pn.Node("Type2", name="bar", yc=1)
tx.merge(previousNode)
tx.merge(thisNode)
theLink = pn.Relationship(thisNode, "PARTOF", previousNode)
tx.merge(theLink)
tx.commit()
Currently this throws the error
ValueError: Primary label and primary key are required for MERGE operation
the first time it needs to merge a node that it hasn't found (i.e., when creating a node). So then I change the line to:
tx.merge(thisNode,primary_label=list(thisNode.labels)[0], primary_key="name")
Which gives me the error IndexError: list index out of range from somewhere deep in the py2neo source code (....site-packages\py2neo\internal\operations.py", line 168, in merge_subgraph at node = nodes[i]). I tried to figure out what was going wrong there, but I couldn't decipher where the nodes list come from through various connections to other commands.
So, it currently matches and creates a few nodes without problem, but at some point it will match until it needs to create and then fails in trying to create that node (even though it is using the same code and doing the same thing under the same circumstances in a loop). It made it through all 20 rows in my sample once, but usually stops on the row 3-5.
I thought it had something to do with the transactions (see comments), but I get the same problem when I merge directly on the graph. Maybe it has to do with the py2neo merge function finding more identities for nodes than nodes. Maybe there is something wrong with how I specified my primarily label and/or key.
Because this error and code are opaque I have no idea how to move forward.
Anybody have any advice or instructions on merging nodes with py2neo?
Of course I'd like to know how to fix my current problem, but more generally I'd like to learn how to use this package. Examples, instructions, real documentation?
I am having a similar problem and just got done ripping my hair out to figure out what was wrong! SO! What I learned was that at least in my case.. and maybe yours too since we got similar error messages and were doing similar things. The problem lied for me in that I was trying to create a Node with a __primarykey__ field that had a different field name than the others.
PSEUDO EXAMPLE:
# in some for loop or complex code
node = Node("Example", name="Test",something="else")
node.__primarykey__ = "name"
<code merging or otherwise creating the node>
# later on in the loop you might have done something like this cause the field was null
node = Node("Example", something="new")
node.__primarykey__ = "something"
I hope this helps and was clear I'm still recovering from wrapping my head around things. If its not clear let me know and I'll revise.
Good luck.

making objects constantly in a while loop

I'm doing a project for a year 11 physics class and I'm trying to make a battery that generates electrons. This is the code:
electron = sphere(radius = 1, color = color.yellow, vel = vec(-1,0,0));
while battery.voltage > 0:
eb = electron.clone(pos=vec(0,0,0), vel = vec(-1,0,0));
I'm trying to make "eb" constantly, but it only applies eb.pos = eb.pos + eb.vel * deltat; apply to a the first electron. Is there any way to do this without making 600 different electron objects?
You could change the attribute that is modified directly to the electron object instead of creating it all the time. Apply the modifications to electron and add the computing action in the while. Is it what you meant?
You definitely need to make and move 600 sphere objects in order to have 600 sphere objects move. Your variable "eb" is just the name of the most recently made clone of the original sphere.
I'll advertise that a better place to pose VPython questions is in the VPython forum at
https://groups.google.com/forum/?fromgroups&hl=en#!forum/vpython-users

Load Excel add-in

I tried:
$sAddIn = "H:\prog\essxleqd.xla"
$oExcel = ObjCreate("Excel.Application")
$oExcel.Visible = 1
$oExcel.WorkBooks.Add
$oAddIn = $oExcel.AddIns.Add($sAddIn)
$oAddIn.Installed = True
$oExcel.WorkBooks.Open("H:\Balance_Inquiry.xls")
When I do:
Run('"c:\pathtoexcel\excel.exe" "c:\pathtoaddin\addin.xla"')
It will work. But I prefer the former solution because I need two different add-ins.
$sAddIn = "H:\prog\essxleqd.xla"
$oExcel = ObjCreate("Excel.Application")
$oExcel.Visible = 1
$oExcel.WorkBooks.Add
$oAddIn = $oExcel.AddIns.Add($sAddIn)
$oAddIn.Installed = False
$oAddIn.Installed = True
$oExcel.WorkBooks.Open("H:\Balance_Inquiry.xls")
This seems to do the trick. First time it got installed and worked. Afterwards it didn't. Even when it is installed it doesn't execute the second time. Maybe someone can explain or provide a more elegant solution?
Strange problem indeed. It seems that the addon will only do its operations when you install it? That is not how Excel addons should behave, and that is why you are seeing strange behavior when trying to automate it.
If the addon needs to be reinstalled to work, then indeed the only solution is to reinstall the addon.
$oAddIn.Installed = False
$oAddIn.Installed = True
If this is an addon that is written by you or someone in your own business, then you might want to identify the problem in the addon itself. I can safely assure you that the normal mode of operation works well. :))
As a bonus tip, you might want to do this:
$oAddIn = $oExcel.AddIns.Add($sAddIn, True)
It will copy the file to the appropriate location if that is necessary, otherwise it is left alone.

In MATLAB, how do I plot to an image and save the result without displaying it?

This question kind of starts where this question ends up. MATLAB has a powerful and flexible image display system which lets you use the imshow and plot commands to display complex images and then save the result. For example:
im = imread('image.tif');
f = figure, imshow(im, 'Border', 'tight');
rectangle('Position', [100, 100, 10, 10]);
print(f, '-r80', '-dtiff', 'image2.tif');
This works great.
The problem is that if you are doing a lot of image processing, it starts to be real drag to show every image you create - you mostly want to just save them. I know I could start directly writing to an image and then saving the result. But using plot/rectangle/imshow is so easy, so I'm hoping there is a command that can let me call plot, imshow etc, not display the results and then save what would have been displayed. Anyone know any quick solutions for this?
Alternatively, a quick way to put a spline onto a bitmap might work...
When you create the figure you set the Visibile property to Off.
f = figure('visible','off')
Which in your case would be
im = imread('image.tif');
f = figure('visible','off'), imshow(im, 'Border', 'tight');
rectangle('Position', [100, 100, 10, 10]);
print(f, '-r80', '-dtiff', 'image2.tif');
And if you want to view it again you can do
set(f,'visible','on')
The simple answer to your question is given by Bessi and Mr Fooz: set the 'Visible' setting for the figure to 'off'. Although it's very easy to use commands like IMSHOW and PRINT to generate figures, I'll summarize why I think it's not necessarily the best option:
As illustrated by Mr Fooz's answer, there are many other factors that come into play when trying to save figures as images. The type of output you get is going to be dependent on many figure and axes settings, thus increasing the likelihood that you will not get the output you want. This could be especially problematic if you have your figures set to be invisible, since you won't notice some discrepancy that could be caused by a change in a default setting for the figure or axes. In short, your output becomes highly sensitive to a number of settings that you would then have to add to your code to control your output, as Mr Fooz's example shows.
Even if you're not viewing the figures as they are made, you're still probably making MATLAB do more work than is really necessary. Graphics objects are still created, even if they are not rendered. If speed is a concern, generating images from figures doesn't seem like the ideal solution.
My suggestion is to actually modify the image data directly and save it using IMWRITE. It may not be as easy as using IMSHOW and other plotting solutions, but I think it is more efficient and gives more robust and consistent results that are not as sensitive to various plot settings. For the example you give, I believe the alternative code for creating a black rectangle would look something like this:
im = imread('image.tif');
[r,c,d] = size(im);
x0 = 100;
y0 = 100;
w = 10;
h = 10;
x = [x0:x0+w x0*ones(1,h+1) x0:x0+w (x0+w)*ones(1,h+1)];
y = [y0*ones(1,w+1) y0:y0+h (y0+h)*ones(1,w+1) y0:y0+h];
index = sub2ind([r c],y,x);
im(index) = 0;
im(index+r*c) = 0;
im(index+2*r*c) = 0;
imwrite(im,'image2.tif');
I'm expanding on Bessi's solution here a bit. I've found that it's very helpful to know how to have the image take up the whole figure and to be able to tightly control the output image size.
% prevent the figure window from appearing at all
f = figure('visible','off');
% alternative way of hiding an existing figure
set(f, 'visible','off'); % can use the GCF function instead
% If you start getting odd error messages or blank images,
% add in a DRAWNOW call. Sometimes it helps fix rendering
% bugs, especially in long-running scripts on Linux.
%drawnow;
% optional: have the axes take up the whole figure
subplot('position', [0 0 1 1]);
% show the image and rectangle
im = imread('peppers.png');
imshow(im, 'border','tight');
rectangle('Position', [100, 100, 10, 10]);
% Save the image, controlling exactly the output
% image size (in this case, making it equal to
% the input's).
[H,W,D] = size(im);
dpi = 100;
set(f, 'paperposition', [0 0 W/dpi H/dpi]);
set(f, 'papersize', [W/dpi H/dpi]);
print(f, sprintf('-r%d',dpi), '-dtiff', 'image2.tif');
If you'd like to render the figure to a matrix, type "help #avifile/addframe", then extract the subfunction called "getFrameForFigure". It's a Mathworks-supplied function that uses some (currently) undocumented ways of extracting data from figure.
Here is a completely different answer:
If you want an image file out, why not just save the image instead of the entire figure?
im = magic(10)
imwrite(im/max(im(:)),'magic.jpg')
Then prove that it worked.
imshow('magic.jpg')
This can be done for indexed and RGB also for different output formats.
You could use -noFigureWindows to disable all figures.

Resources