Monday, April 30, 2012

Parallel delaunay triangulation naive algorithm

The following code(Pg.187,Computational Geom in C by Rourke) takes same time to run serially as well as in parallel(2 proc).
Please help me identify the problem.
Here's the parallel portion



int chunk;
chunk=10;
#pragma omp parallel private(i,j,k,xn,yn,zn)
{
#pragma omp for schedule(static,chunk)
for(i=0;i<n-2;i++)
{
for(j=i+1;j<n;j++)
for(k=i+1;k<n;k++)
if(j!=k)
{
xn=(y[j]-y[i])*(z[k]-z[i])-(y[k]-y[i])*(z[j]-z[i]);
yn=(x[k]-x[i])*(z[j]-z[i])-(x[j]-x[i])*(z[k]-z[i]);
zn=(x[j]-x[i])*(y[k]-y[i])-(x[k]-x[i])*(y[j]-y[i]);
if(flag=(zn<0))
for(m=0;m<n;m++)
flag=flag && ((x[m]-x[i])*xn + (y[m]-y[i])*yn + (z[m]-z[i])*zn <=0);
if (flag)
printf("%d\t%d\t%d\n",i,j,k);
}
}
}




Response.Redirect behaves different from within UpdatePanel

Everywhere in my web application i use redirects like these:



Response.Redirect("~/SearchResults.aspx", true); 


And this always takes me to the right page. http://localhost/myapp/SearchResults.aspx



But now i'm doing this in the onclick event of a button that sits in an ASP.NET UpdatePanel and it tries to bring me to the following address:
http://localhost/myapp/%2fmyapp%2fSearchResults.aspx



Does anyone have an idea how to fix this?





UITableView with Core Data ordered by time, not alphabetically

I'm working on an app that uses Core Data and a UITableView. What I've noticed is that when I add a new TableView entry, the cells seem to order alphabetically. Is there a way to make it so the cells are ordered by the time I add them (from top to bottom) rather than by the alphabet. Thanks!





MYSQL ordering columns in my query

I have been working on trying to get a bunch of data to work in a table structure displayed neatly using PHP, and I must say I am having a difficult time. I have finally been able to call the columns so that in case I add a field it will always add it in my table, and I hope for this to be very easily managed. However, when I initially set up the table, I put it in a random order. Now when I come use the DESCRIBE table it gives them to me in exact order, and I cannot find a way to organize them better. It would not make sense to say have month/year at the end of the database for my form that I have.



<?php 
require 'connect.php';
?>
<h3>Monthly Finances | <a href="new.php">Add New Month</a> </h3>
<table border="1" bordercolor ="#000000">
<tr>
<?php
$columns = "DESCRIBE `month` ";
if($query_run_columns = mysql_query($columns)){
$columnNames = array();
while($column = mysql_fetch_assoc($query_run_columns)){
echo '<th>'.$column['Field'].'</th>';
}
}else{
echo'sql error';
}

?>


<?php
$gatherdata = "SELECT `month`, `year`,`rent`,`electric`,`cable`,`cellphone`,`renters` FROM `month` ";
if($query_run = mysql_query($gatherdata)){

while($row = mysql_fetch_assoc($query_run)){
$rent = $row['rent'];
$electric = $row['electric'];
$cable = $row['cable'];
$cellphone = $row['cellphone'];
$renters = $row['renters'];
$month = $row['month'];
$year = $row['year'];

echo '<tr>';
echo '<td align="center">'.$month.'</td>';
echo '<td algin="center">'.$year.'</td>';
echo '<td align="center">'.$rent.'</td>';
echo '<td align="center">'.$electric.'</td>';
echo '<td align="center">'.$cable.'</td>';
echo '<td align="center">'.$cellphone.'</td>';
echo '<td align="center">'.$renters.'</td>';
echo '</tr>';
}
}else{
echo 'query error';
}
?>
<br>View by month
</table>
<form action="index.php" method="GET">
<select name="months" value="all">
<?php
$gathermonths = "SELECT `month`, `year` FROM `month";

if($query_month_selector = mysql_query($gathermonths)){
while($month_row = mysql_fetch_assoc($query_month_selector)){
$month = $month_row['month'];
$year = $month_row['year'];

echo '<option value="'.$month.' '.$year.'">' .$month.' '.$year.'</option>';
}
}
echo $_GET['months'];
?>
<input type="submit" value="View Selected Date"></input>
</select>
</form>


My code is very far from complete, or orderly but I have been slacking on this project and I will clean it up more when I have more time. But if you could please give me a hand on an efficient organizational method that would be appreciated.





Android: Append not shown ActionItems to Icon instead of Context Menu

I found an example how to use a context menu with actionBar. This example waits for clicks on the phones menu button. But I want to have it appended to the icon or better the activity name. thanks



  public class menu extends Activity {

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_fragen, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
..




StringBuilder Append vs AppendFormat efficiency in C#

Which is more efficient in C#, 1 or 2?



StringBuilder sb = new StringBuilder();
sb.Append("my string " + myVar + " my string"); // 1
sb.AppendFormat("my string {0} my string", myVar); // 2


I'm guessing that the question could also be rephrased:



string y = "my string " + myVar + " my string";              // 1
string x = String.Format("my string {0} my string", myVar); // 2




Ruby is very slow

I have a PC with 2 processors of 2GHz and 4go of ram. I use RVM with ruby-1.9.3-p194-perf and rails 3.2.3. When I load my rails application, it take a few time and I think it's not normal.



This is some example :



time rails new speed_test
...
real 0m7.240s
user 0m4.484s
sys 0m0.184s

time rails g scaffold Articles title:string description:text
...
real 0m4.910s
user 0m4.052s
sys 0m0.348s

time rake db:migrate
...
real 0m4.172s
user 0m3.716s
sys 0m0.244s

time rake
...
real 0m15.981s
user 0m14.045s
sys 0m1.048s


This is some short commands but, with some hundred of tests, it's very long, even with spork.



Do you have a solution?



Thanks a lot!





Match comma separated list with Ruby Regex

Given the following string, I'd like to match the elements of the list:




foo,bar,baz




The minimum number of elements is 1, and there can be arbitrarily many. Assume no whitespace and lower case.



I've tried this, which should work, but doesn't populate all the match groups for some reason:



^([a-z]+)(?:,([a-z]+))*



That matches foo in \1 and baz (or whatever the last element is) in \2. I don't understand why I don't get a match group for bar.



Any ideas?



EDIT: Ruby 1.9.3, if that matters.



EDIT2: Rubular link: http://rubular.com/r/cDQh9SZyA2





Dividing an application with Spring and Mybatis into multiple modules

I'd like to divide my project into multiple maven modules. But I'm not sure of what structure would be preferable. The main goal is to take out the service logic in a separate module.



Right now I have four packages in my project: controller, domain, persistence, service. Say, this can be divided into two main parts: database related stuff (domain and persistence packages) and the service part (service and, oh, maybe a controller). Is this a good structure? Do service and controller packages seem to be a good separated service? I'm pretty sure it's better to put service and controller parts in a single module due to the fact they are autowired now (and also logically wired). Should each child module be a web application of a full value (obviously with a lack of packages and files)?



And I'm not sure about the placement of the web pages. Should they all be in a Spring parent module? That would make sense. But different pages could also be in different web-app modules (I guess), and that also makes sense.



I understand that this question doesn't seem to be a concrete one. It's because I don't have a formed understanding of a preferable (and also of a working) structure. An advice would be appreciated, thanks in advance.





Visual C++ Undo and Redo operations

I have a rather large application I'm trying to make in Visual-C++, and I am now trying to add undo/redo functionality.



Having a rather large amount of events (button clicks, label text changed, etc.), I would like to find a way to undo/redo without adding code to every function.
For Instance, I would like a class that can read every event done and store it automatically. Then in my undo/redo events, I can just get the latest action stored.



If that is not possible, I would not mind some other way.



Any help?





Tomcat memory consumption is more than heap + permgen space

I am observing a mismatch in Tomcat RAM consumption between what the OS says and what jVisualVM says.



From htop, the Tomcat JVM is has 993 MB of resident memory



From jVisualVM, the Tomcat JVM is using




  • Heap Max: 1,070,399,488 B

  • Heap Size: 298.438.656 B

  • Heap Used: variable, between 170MB and and 270MB

  • PermGen Max: 268,435,456 B

  • PermGen Size: 248,872,960 B

  • PermGen Used: slightly variable, around 150MB



From my understanding the OS memory consumption should be Heap Size + PermGen Size ~= 522 MB. But that's 471 MB less than what I'm observing.



Anyone got an idea what am I missing here?



PS: I know that my max heap is much higher than what is used, but I'm assuming that should have no effect if the JVM does not use it (i.e. Heap Size is lower).



Thanks!
Marc





Java Bit Operation on Long - Removing some bits

I have a long number. Now, what I want to do is the following:



long l = "001000......10001100000" (bits representation)


I need to remove the 3rd and 4th bits of it (i.e. 10) from the left and convert the remaining 62 bits to long



long newl = "0000......10001100000" (bits representation)


Can anybody help me do this efficiently in Java ?





Why is System.Random giving '1' a lot of times in a row, then not for a while, then again?

Not sure how else to explain this, so the title pretty much describes the problem.



Random is not being re-initialised every part of the loop. It's a static member of a class which I always call on from other classes.



I am not using a custom seed.



The initialisation code is:



    public static Random random = new Random();

for (int x = 0; x < 75; x++)
{
if (main.random.Next(11) == 1)
{
tiles[heightMap[x] - 1][x] = 4;
tiles[heightMap[x] - 2][x] = 4;
tiles[heightMap[x] - 3][x] = 4;
tiles[heightMap[x] - 4][x] = 4;
tiles[heightMap[x] - 5][x] = 4;
tiles[heightMap[x] - 5][x - 1] = 5;
tiles[heightMap[x] - 6][x - 1] = 5;
tiles[heightMap[x] - 6][x] = 5;
tiles[heightMap[x] - 5][x + 1] = 5;
tiles[heightMap[x] - 6][x + 1] = 5;
}
}


This (Ignore my ugly hax for making a tree, it's rudimentary and temporary) generates a tree.



However my terrain often looks like:



AIR AIR AIR AIR TREE TREE TREE AIR AIR TREE TREE AIR AIR AIR AIR TREE TREE TREE



As in it seems to get clusters of 1 at a time.



Can anyone give insight into why this is happening? Is there a better alternative than using the System.Security.Cryptography.Random class (Since that's slower and this is a game not a bank program I want it to have very fast loading speeds)



I'd expect an average of 9 gap per tree, but it's more like 7 and then 3 trees closely clustered together.



enter image description here





Assignment = operator overloading

Please help to complete this execution of an assignment overloading function.



Here is the instruction:



Assignment operator (=) which will copy the source string into the destination string. Note that size of the destination needs to be adjusted to be the same as the source.



Both addition (+) and assignment (=) operators need to be capable of cascaded operations. This means String3 = String1 + String2, or String1 = String2 = String3 should work.



Here is my .cpp file:



MyString& MyString::operator=(const MyString& rhs)
{

if(this != &rhs)
{

delete [] String;
String = new char[Size];

for(int i = 0; i < counter+1 ; i++)
{
String[i] = rhs.String[i];
}


}
return *this;

}


It is called in the main.cpp file by:



String1=String2=String3;



I feel as though I am missing something.Help!!





Bitwise shifting array of char's

I've got an array of char's that I'm trying to bitwise shift right, then "&" with another array. I think I've got the wrong idea of how to do this. I thought, even though it was an array of char's just stating "my_array >>= 1" would shift everything but I'm getting a: "error: invalid operands to binary >> (have 'char[8]' and 'int')"

The bitwise comparision I'm trying to do is with a similar size array initiated to all "0's"...for that I'm getting: "error: invalid operands to binary & (have 'char *' and 'char *')" Do I need to convert these array's into something else before I can shift and compare?





How to consume command line arguments using raw_input() instead of sys.argv

I am new to python I have developed the following code for some online coding submission. Now my problem is this coding site is not accepting sys.argv. How do I convert this code to take raw_input from command line. raw_input is confusing as compared to sys.argv. Please help. Thanks in advance.



import sys
ln = int(sys.argv[1])
#create list of elements which are sum of two command line input
list = []
i = 2
while i <= ln:
sum = int(sys.argv[i]) + int(sys.argv[i+1])
list.append(sum)
i = i + 2
#update list with elements which are sum of the two elements within the list
j = 0
while j < len(list) - 1:
list.append(list[j]+list[j+1])
j = j + 2
#get final sum using addition of all the elements in the list
k = 0
sum = 0
while k < len(list):
sum = sum + list[k]
k = k + 1
print sum




How to allow users to edit a post using the sql UPDATE statement?

I am trying to let users edit the content that they post. The content is seperated into two sections the title and the text. It also has a category but I don't want to let them edit that. So here is the code that is suppose to update any changes to the title:




$sql = "UPDATE



topics



SET topic_subject = " . mysql_real_escape_string($_POST['topic_subject']) . "



WHERE



topic_id = " . mysql_real_escape_string($_GET['id']);




The code that updates the content has the same format.
I get the id from the url of the page and once they click submit on the editing page the form calls the page that contains this code. It gives me this error:




An error occurred while inserting your data. Please try again later.



You have an error in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'WHERE topic_id =' at line 4




I am not an expert in SQL and don't know what the problem could be. Thanks in advance.





Java: How do I simulate probability?

I have a set of over 100 different probabilities ranging from 0.007379 all the way to 0.913855 (These probabilities were collected from an actuary table http://www.ssa.gov/oact/STATS/table4c6.html). In Java, how can I use these probabilities to determine whether something will happen or not? Something along these lines...



public boolean prob(double probability){
if (you get lucky)
return true;
return false;
}




multiple automated tasks to run ubuntu 10.04 server

I need to run automated tasks every 15. The tasks is for my server (call it server A, Ubuntu 10.04 LAMP) to query for updates to another server (Server B).



I have multiple users to query for, possibly 14 (or more) users. As of now, the scripts are written in PHP. They do the following:




  1. request Server B for updates on users

  2. If Server B says there are updates, then Server A retrieves the updates

  3. In Server A, update DB with the new data for the users in

  4. run calculations in server A

  5. send prompts to users that I received data updates from.



I know cron jobs might be the way to go, but there could be a scenario where I might have a cron job for every user. Is that reasonable? Or should I force it to be one cron job querying data for all my users?



Also, the server I'm querying has a java api that I can use to query it. Which means I could develop a java servlet to do the same. I've had trouble with this approach but I'm looking for feedback if this is the way to go. I'm not familiar with Tomcat and I don't fully understand it yet.



Summary: I need my server to run tasks automatically every 15 mins, the requests data from another server, updates its DB and then send prompts to users. What's are recommended approaches?



Thanks for your help!





How to use parent viewcontroller to launch uiactionsheet so that it does not get clipped?

Hey so I have a problem where I am inserting an actionsheet into a view that is inside of a scrollview in a different view controller. The actionsheet works just fine, the problem is that if i go down at all in the scrollview the actionsheet gets clipped off. I've tried several solutions with no luck. I think the problem is that the actionsheet is being inserted into the view that is placed inside the scrollview. Anyone have any idea how to launch the action sheet from the view controller that the scrollview is in instead? Here is how I am trying to do it right now:



When a button is touched it calls this method:



- (IBAction)callDP:(id)sender {

UIButton *selectedButton = (UIButton *)sender;

actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];

[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];

CGRect pickerFrame = CGRectMake(0, 40, 0, 0);

datePickerView = [[UIDatePicker alloc] initWithFrame:pickerFrame];
datePickerView.tag = 10;

[datePickerView addTarget:self action:@selector(changeDate:) forControlEvents:UIControlEventValueChanged];

[actionSheet addSubview:datePickerView];
[actionSheet setTitle:@"Start Date"];
UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Done"]];
closeButton.momentary = YES;
closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
closeButton.tintColor = [UIColor blackColor];
[closeButton addTarget:self action:@selector(dismissActionSheet) forControlEvents:UIControlEventValueChanged];
[actionSheet addSubview:closeButton];


datePickerView.datePickerMode = UIDatePickerModeDate;


//THIS IS THE PART THAT I THINK I AM HAVING THE PROBLEM WITH

// [actionSheet showFromToolbar:self.toolbarItems];
//[actionSheet showFromTabBar:self.parentViewController.tabBarController.tabBar];
[actionSheet showInView:self.parentViewController.view];


}


Here is where I insert the view into the scrollview. I have it set up so that I am using a view from a different uiviewcontroller class to control everything. The reason I do that is so that i can have the scrollable part, but be able to visually create everything that I need without having to do it programmatically....I apologize if that is kind of confusing. I can clarify if needs be...but here it is. The viewcontroller class that contains the view I want to put into the scroll view is called registration page. Its inside of registrationPage that it calls the actionSheet. Let me know what you think...



registrationPage = [[RegistrationPageToInsertViewController alloc]init];

viewToInsert = registrationPage.view;

[scrollView addSubview:viewToInsert];
[scrollView setContentSize:viewToInsert.frame.size];
// [scrollView sendSubviewToBack:imgView];

//scrollView.contentSize=CGSizeMake(320,416);
[self.view bringSubviewToFront:scrollView];