Monday, April 30, 2012

Mouse control not responding

I've just started using pygame. I've created my game but it's really unstable and crashes (having issues exiting).



I've created a welcome page but it has created a bug with game control (the character controlled by the mouse has stopped responding), I've tried few methods but just results in more game crashes and errors. can you please help me out to debug anything you might spot. you download the game from her http://dl.dropbox.com/u/47312995/Twerk.rar



the code:



import pygame
from pygame import *
import random
import time
import os
import sys
from pygame.locals import *


black = (0,0,0)
white = (255,255,255)

pygame.init()

def game():

os.environ['SDL_VIDEO_CENTERED'] = '1'
mouse.set_visible(False)
screen = display.set_mode((800,500))
backdrop = pygame.image.load('bg.jpg').convert_alpha()
menu = pygame.image.load('green.jpg').convert_alpha()
ballpic = pygame.image.load('ball.gif').convert_alpha()
mouseball = pygame.image.load('mouseball.gif').convert_alpha()
display.set_caption('Twerk')
back = pygame.Surface(screen.get_size())

def text(text,x_pos,color,font2=28):
tfont = pygame.font.Font(None, font2)

text=tfont.render(text, True, color)
textpos = text.get_rect(centerx=back.get_width()/2)
textpos.top = x_pos
screen.blit(text, textpos)

start = False
repeat = False
while start == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
start = True
#falling = True
#finish = True

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
start = True
#game over screen
screen.blit(menu,[0,0])
pygame.display.set_caption("TWERK")

#Text
#"Welcome to Escape"
#needs replacing with logo
text("Twerk",60,white,300)

#"Instructions"
text("Instructions",310,white)
text("----------------------------------------------------------------------------------------",320,white)
text("Avoid the the enemies",340,white)
text("Last as long as you can!",360,white)
text("Press space to start",420,white)
pygame.display.flip()


while start == True:
positionx=[]
positiony=[]
positionxmove=[]
positionymove=[]
falling = False
finish = False
score=0
enemies=1
velocity=1

for i in range(enemies):
positionx.append(random.randint(300,400)+random.randint(-300,200))
positiony.append(random.randint(200,340)+random.randint(-200,100))
positionxmove.append(random.randint(1,velocity))
positionymove.append(random.randint(1,velocity))


font = pygame.font.Font(None, 28)
text = font.render('Starting Twerk... ', True, (100,100,100))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery

screen.blit(backdrop, (0,0))
screen.blit(text, textRect)
pygame.display.update()
game=time.localtime()

while start == True:
end=time.localtime()
score= (end[1]-game[1])*3600 + (end[4]-game[4])*60 + end[5]-game[5]
if score > 1: break

first=True
strtTime=time.localtime()

while not finish or falling:
screen.blit(backdrop, (0,0))
for i in range(enemies):
screen.blit(ballpic,(positionx[i],positiony[i]))
(mousex,mousey)=mouse.get_pos()
screen.blit(mouseball,(mousex,mousey))
display.update()
strt = time.localtime()

if first:
while True:
end=time.localtime()
score= (end[3]-strt[3])*3600 + (end[4]-strt[4])*60 + end[5]-strt[5]
if score > 3: break
first = False

if falling:
for i in range(enemies):
positionymove[i]=1000
positionxmove[i]=0


for i in range(enemies): positionx[i]=positionx[i]+positionxmove[i]
for i in range(enemies): positiony[i]=min(600,positiony[i]+positionymove[i])

if falling:
falling=False
for posy in positiony:
if posy<600: falling=True


if not falling:
for i in range(enemies):
for j in range(i+1,enemies):
if abs(positionx[i]-positionx[j])<20 and abs(positiony[i]-positiony[j])<20:
temp=positionxmove[i]
positionxmove[i]=positionxmove[j]
positionxmove[j]=temp
temp=positionymove[i]
positionymove[i]=positionymove[j]
positionymove[j]=temp

for i in range(enemies):
if positionx[i]>600: positionxmove[i]*=-1
if positionx[i]<0: positionxmove[i]*=-1
if positiony[i]>440: positionymove[i]*=-1
if positiony[i]<0: positionymove[i]*=-1

for i in range(enemies):
if abs(positionx[i]-mousex)<40 and abs(positiony[i]-mousey)<40:

endTime=time.localtime()
score= (endTime[3]-strtTime[3])*3600 + (endTime[4]-strtTime[4])*60 + endTime[5]-strtTime[5]
falling = True
finish = True
game()


Thank you in advance





Can't return xmlhttp.responseText?

Any insight into the problem here? When run, the code yields nothing. No text appears on the page. If I uncomment the commented line, the xml results appear. Why can't I pass it as a variable? (I do get the alert, fyi, so the function is being called.)



 <script type="text/javascript">
function loadXMLDoc(parameterString)
{
alert("loadXMLDoc has been called.");
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{

//document.getElementById("xmlResults").innerHTML = xmlhttp.responseText;
alert("Got the response!");
return xmlhttp.responseText;
}
else document.getElementById("xmlResults").innerHTML = "No results."
}

var url = "http://metpetdb.rpi.edu/metpetwebsearchIPhone.svc?" + parameterString;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>



<script type="text/javascript">

$(function(){

//left out irrelevant code which creates the var "parameters"

var results = loadXMLDoc(parameters);

document.getElementById("xmlresults").innerHTML = results;

});


</script>


<body>
<div id="xmlresults"></div>
</body>




Android: Constantly Update Map With Coordinates from Web Service

Hello I am writing an app that makes the use of coordinates from a webserver. I know how to retrieve the coordinates from the webservice, but once I get them how can I constantly display them on the map. Sort of like the Location Listener updates the point on the map when the location from the location manager changes. I want to constantly update the points I receive from the webservice.
Is this done with a Service? If so how?



        public class GeoUpdateHandler implements LocationListener {  

@Override
public void onLocationChanged(Location location) {
...
GeoPoint point = new GeoPoint(lat, lng);
createMarker();
mapController.animateTo(point); // mapController.setCenter(point);
}


UPDATED: Code for Createmarker



private void createMarker() {  
GeoPoint p = mapView.getMapCenter();
OverlayItem overlayitem = new OverlayItem(p, "", "");
itemizedoverlay.addOverlay(overlayitem);
mapView.getOverlays().add(itemizedoverlay);
}


UPDATED: Code for getting coordinates from webservice...



HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(".../android/serverFile.php");
JSONObject json = new JSONObject();
try {
JSONArray postjson=new JSONArray();
postjson.put(json);
// Execute HTTP Post Request
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
// for JSON:
if(response != null)
{
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String jsonStr = sb.toString();
JSONObject jsonObj = new JSONObject(jsonStr);
String longitudecord = jsonObj.getString("lon");
String latitudecord = jsonObj.getString("lat");


}





Android custom listview with edit text,button and label

i want to make an custom list view in which there should be button edittext and textview and below listview there should be one button with text as Add New and when user click the Add New button the same widget that are in first row of listview should display in second row of list view and again when user click to Add New button same things should happen .
please help me with full xml and java code



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<ListView android:id="@+id/android:list" android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ListView>

<LinearLayout android:id="@+id/linearLayout1"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<Button android:text="Time" android:layout_weight="1" android:id="@+id/btntime" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<EditText android:text="" android:layout_weight="1" android:id="@+id/ettext"
android:layout_width="70dp" android:layout_height="wrap_content"></EditText>
<Button android:text="Record" android:layout_weight="1" android:id="@+id/btnRecord"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="alert" android:layout_weight="1" android:id="@+id/btnAlert"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

<Button android:layout_width="wrap_content"
android:layout_marginLeft="230dp" android:layout_height="wrap_content"
android:id="@+id/btnAddNew" android:text="Add new"></Button>
</LinearLayout>


java code



public class some extends ListActivity implements OnClickListener {
Button add_time, enter_text, record, alert_alarm,add_new;
TimePicker time_picker;
View vw;
AlertDialog.Builder alertdialog;
int mHour,mMinute;
@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.some);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.widgets, null, null, null);
this.setListAdapter(adapter);

add_time = (Button) findViewById(R.id.btntime);
add_time.setOnClickListener(this);
add_new=(Button) findViewById(R.id.btnAddNew);

add_new.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
Toast.makeText(getApplicationContext(), "hi", 1000).show();


}
});
}

public void onClick(View v) {
showDialog(0);
}

@Override
protected Dialog onCreateDialog(int id)
{
alertdialog=new AlertDialog.Builder(this);
switch (id)
{
case 0:

LayoutInflater layout_inflater=getLayoutInflater();
vw=layout_inflater.inflate(R.layout.widgets, null);
alertdialog.setView(vw);
alertdialog.setIcon(R.drawable.icon);
alertdialog.setTitle("Select time");
time_picker=(TimePicker) vw.findViewById(R.id.timepicker);
time_picker.setIs24HourView(false);
alertdialog.setNegativeButton("cancel",new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub

}
});
alertdialog.setPositiveButton("set", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which)
{
add_time=(Button) findViewById(R.id.btntime);
mHour=time_picker.getCurrentHour();
mMinute=time_picker.getCurrentMinute();
if (mHour>12)
{
add_time.setText((mHour-12)+":"+mMinute+" "+"PM");
}
if (mHour==12)
{
add_time.setText("12"+":"+mMinute+" "+"PM");
}
if (mHour<12)
{
add_time.setText(mHour+":"+mMinute+" "+"AM");
}

}
});
alertdialog.show();
}
return super.onCreateDialog(id);
}
}




Writing an LLVM Pass

i'm trying to create an LLVM pass using the guide at http://llvm.org/releases/2.9/docs/WritingAnLLVMPass.html

but i'm having several problems:




  • i haven't many of the folder that are indicated into the guide (lib/Transform/Hello) and (Debug+Asserts), i have created them, is it right? what's the right path?
    i create these: /usr/lib/llvm-2.9/lib/Transforms/Hello and /usr/lib/llvm-2.9/Debug+Asserts


  • when i try to make the file in the guide i have error:




.



# Makefile for hello pass


# Path to top level of LLVM heirarchy
LEVEL = /usr/lib/llvm-2.9/build #*********I MODIFY THIS!!!! ***************

# Name of the library to build
LIBRARYNAME = Hello

# Make the shared library become a loadable module so the tools can
# dlopen/dlsym on the resulting library.
LOADABLE_MODULE = 1

# Tell the build system which LLVM libraries your pass needs. You'll probably
# need at least LLVMSystem.a, LLVMSupport.a, LLVMCore.a but possibly several
# others too.
LLVMLIBS = LLVMCore.a LLVMSupport.a LLVMSystem.a

# Include the makefile implementation stuff
include $(LEVEL)/Makefile.common


and i modify also other lines into Makefile.common:



ifndef LLVM_SRC_ROOT
include $(LEVEL)/Makefile.rules
else
include $(LLVM_SRC_ROOT)/Makefile.rules
endif


because it doesn't find the Makefile.rules (in this way it works)



but now i have this error when i do make into the folder containing my hello.c file (/usr/lib/llvm-2.9/lib/Transforms/Hello):



make: ***  No rule to make target "/configure", needed by "/config.status".  Stop.


what's the problem?!?





Save SQLite database

In my application, I'm using a database to store some data, but if I close my app, my database will be deleted too. So I want to know if there is any mean to save my database and re-use it for the next launch of my app.



I use for the moment
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

in order to create my database.



Thanks for your help





Regarding expressing array in simpler terms

I am developing application..



    class Wheel {
private int size;

Wheel(int s) {
size = s;
}

void spin() {
System.out.print(size + " inch wheel spinning, ");
}

}

public class Bicycle {
public static void main(String[] args) {
Wheel[] wa = { new Wheel(15), new Wheel(17) };
for (Wheel w : wa)
w.spin();
}
}


But Please advise that how could we express Wheel[] wa = { new Wheel(15), new Wheel(17) }; in more simpler terms.





Can ASP.NET MVC3 Applications Host in cloud without specific code changes?

I had created an asp.net web app using:



-ASP.NET MVC 3 Webforms

-Linq to sql

-MSsql server database.

-WCF



What would need to be done to host it on a cloud service? Should i convert it in to Azure application or not. can i directly upload my ASP.Net MVC Web application in a Cloud without specific code changes that would be required before hosting.





llvm pass error

i'm using this guide: http://llvm.org/releases/3.0/docs/WritingAnLLVMPass.html for creating an llvm pass, but i have the following error when i use



opt -load ../../../Debug+Asserts/lib/Hello.so -hello < hello.bc > /dev/null


Error opening '../../../Release/lib/Hello.so': ../../../Release/lib/Hello.so: undefined symbol: _ZN4llvm12PassRegistry12registerPassERKNS_8PassInfoEb
-load request ignored.
opt: Unknown command line argument '-hello'. Try: 'opt -help'


note that i haven't the folder "Debug+Asserts" but "Release"



someone know what's the problem?



maybe because for creating the Hello.bc file i use llvm-clang instead of llvm-gcc? (this guide says to use llvm-gcc but it doesn'n work: llvm.org/releases/3.0/docs/GettingStarted.html#tutorial) or maybe because i have opt version 2.8 while i'm using llvm-3.0 ?





Android:drag and drop items from one list to another

I am looking for a nice user interface where i can move files from one folder(in phone memory) to another(cloud storage space) using drag and drop..



Can i represent files in my folders as a listView?drag and drop in it?



Can anybody help me with a sample or point me in the right direction or give any info thing regarding this...



Thanks..





.htaccess if directive

in .htaccess I have something like this:



RewriteCond %{REQUEST_URI} (\/out\/pictures\/)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (\.jpg|\.gif|\.png)$ core/utils/getimg.php


I want to change it to



RewriteCond %{REQUEST_URI} (\/out\/pictures\/)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
if url == www.mysite.com {
RewriteRule (\.jpg|\.gif|\.png)$ core/utils/getimg.php
} else {
RewriteRule (\.jpg|\.gif|\.png)$ core/utils/getimg1.php
}


Is it possible in some way?





RaptureXML kind of slow

I've recently switched from TBXML to RaptureXML, and even though pulling in information is much easier, there is a noticeable delay when I tap the tab bar button containing my xml table view.



In my viewDidLoad method I have the following"



events = [[NSMutableArray alloc] init];

[self loadURL];


And my loadURL method is the following:



- (void)loadURL {

RXMLElement *rootXML = [RXMLElement elementFromURL:[NSURL URLWithString:@"http://api.somexml.com/xml"]];

[rootXML iterateWithRootXPath:@"//event" usingBlock:^(RXMLElement *event) {
[events addObject:[NSArray arrayWithObjects:
[event attribute:@"uri"],
[event attribute:@"displayName"],
[event attribute:@"type"],
nil]];
}];

[rootXML iterateWithRootXPath:@"//location" usingBlock: ^(RXMLElement *location) {
[events addObject:[NSArray arrayWithObjects:
[location attribute:@"city"],
[location attribute:@"lat"],
[location attribute:@"lng"],
nil]];
}];

[rootXML iterateWithRootXPath:@"//start" usingBlock:^(RXMLElement *start) {
[events addObject:[NSArray arrayWithObjects:
[start attribute:@"time"],
[start attribute:@"date"],
nil]];
}];



}


Is there something I can do to speed it up? Also when I assign my row count as [events count] I'm getting 19 rows when I should only get 6. Please help.





jQuery UI Tabs "Select" Event Being Overridden by "Click" Event -- Uncaught TypeError

I'm having some trouble selecting a tab programmatically. My tabs are loading inside a Fancybox dialog window, which is launched on click of a link. Basically, I want to perform certain actions any time a tab is selected, and also select a specific tab when a link is clicked.



I am initializing jQuery UI Tabs with the select event like so:



$('#tabs').tabs({

select: function(event, ui) {

// grab value of a form input
var text = $(someElement).val();

// check its length
if ( text.length > 0 ) {
// do stuff
}
}
})


Later on in my JS file I have the following:



$(document).on('click', 'a.edit', function() {
if($category == 'book') {
// load the tab specific to the 'book' category
$('#tabs').tabs({ selected: 3 });
}
})


When I click the a.edit link for an item in the "book" category, my console throws this error:



Uncaught TypeError: Cannot read property 'length' of undefined


Then, instead of the tabs loading in the Fancybox, nothing happens. This error is not thrown when I click the link for items that are not in the book category. Thus, two things are painfully evident:




  1. I am a n00b

  2. My select event is apparently getting overridden by the click event, so text is not set



I've tried setting a default for text at the top of my JS file but that doesn't work. My question, then, is:



What is the correct way to initialize UI Tabs with a select event, while also being able to programmatically select a tab with a click event?



Or, more concisely,



Why am I getting that damn error?





interestOps throws IllegalArgumentException

I wand send a message to all User in map.



    for (User u : _userMap.values()) {
u.getMessages().add(data);

u.getKey().interestOps(SelectionKey.OP_WRITE);
}


but whene I run this function I see




Exception in thread "main" java.lang.IllegalArgumentException




this line make error



u.getKey().interestOps(SelectionKey.OP_WRITE);


getKey() returns SelectionKey, getMessages returns ArrayList, data is a byte[] array with message I read using channel.read(buffer);



MORE INFO:



In a constructor I make Selector



_selector = Selector.open();


I run server



public void startServer() throws IOException {
while (true) {
_selector.select();

Iterator<SelectionKey> keys = _selector.selectedKeys().iterator();

while (keys.hasNext()) {
SelectionKey key = keys.next();
keys.remove();

if (!key.isValid())
continue;
if (key.isAcceptable())
accept(key);
else if (key.isReadable())
read(key);
else if (key.isWritable())
write(key);
}
}
}


I accept connection



private void accept(SelectionKey key) throws IOException {
ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
SocketChannel channel = serverChannel.accept();
channel.configureBlocking(false);

User u = new User(key);
_userMap.put(channel, u);

channel.register(_selector, SelectionKey.OP_READ);
}


In read function whene I read message I have this for each loop. But whene is one user and I move line with interestOps just behind loop it works.



        //u.getKey().interestOps(SelectionKey.OP_WRITE);
}
key.interestOps(SelectionKey.OP_WRITE);


Full read and write function:



private void read(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();

ByteBuffer buffer = ByteBuffer.allocate(2048);
int read = -1;

try {
read = channel.read(buffer);
} catch (Exception e) {
e.printStackTrace();
}

if (read == -1) {
_userMap.remove(channel);

channel.close();
key.cancel();

return;
}

byte[] data = new byte[read];

System.arraycopy(buffer.array(), 0, data, 0, read);

/// WYSy?A DO WSZYSTKICH. usun??

for (User u : _userMap.values()) {
u.getMessages().add(data);

u.getKey().interestOps(SelectionKey.OP_WRITE);
}
//key.interestOps(SelectionKey.OP_WRITE);

///////
}

private void write(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();

ArrayList<byte[]> msg = _userMap.get(channel).getMessages();
Iterator<byte[]> i = msg.iterator();

while (i.hasNext()) {
byte[] item = i.next();
i.remove();

channel.write(ByteBuffer.wrap(item));
}

key.interestOps(SelectionKey.OP_READ);
}


SOLUTION:



I can't answer my own question now, so put it here:



SelectionKey in accept method is a little handicapped. I tried to replace it with new key in read method and it works. So in User class I don't keep SelectionKey var any more, now I keep SocketChannel. SocketChannel have keyFor method, so whene I have selector I can get key



        u.getChannel().keyFor(_selector).interestOps(SelectionKey.OP_WRITE);




Printing html5 template from within C++ program automatically

I'm trying to find a way through C++ to create a program that fills in an html5(or CSS) text template for user invoices and has it automatically print them. Unfortunately my searches for anything like this has been quite awful as i'm probably missing key terminology to search on.



To keep it organized, I want to:




  • Create an invoice template in html5

  • Fill in various fields with the information inside of a C++ application

  • Have the C++ application automatically print the designed invoice template



Creating the application and invoice are not issues, but rather trying to find a creative way to have it print without the program requiring a user to be present has been. Can anyone guide me towards a solution to do something like this? Thanks for any insight, it's greatly appreciated.





preg_matchvalidation

Okay, everything I've checked on this site referring to validation isn't what I'm looking for.



What I'm looking to do is a minimum length and maximum length of a value in firstname and secondname, this is the code which I currently have.



        if (isset($_POST['submit'])) {
$errors = array();

if (isset($_POST['firstname'])) {
$fn = $_POST['firstname'];
} else {
$errors[] = "You have not entered a first name";
}

if (isset($_POST['secondname'])) {
$sn = $_POST['secondname'];
} else {
$errors[] = "You have not entered a second name";
}


I was just wondering how would I apply preg_match to those which the minimum is 4 letters and the maximum is 15?



I do know it's something to do with



if(preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname']))


In doing this I tried to do



    if (isset($_POST['firstname']) && preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname')) {


But that also gave me an error :/



Could anyone give me a solution for this?



Thanks!



UPDATE:-



Nvm, I found a way around it. I just did this



if (isset($_POST['firstname'])) {
if (preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname'])) {
$fn = $_POST['firstname'];
} else {
$errors[] = "<center> <h3> You must enter between 4 and 15 characters! </h3></center>";
}
} else {
$errors[] = "You have not entered a name";


}
For both the firstname and secondname. :)





Fast in-place partitioning of sorted array into two sorted subarrays

Edit - I removed all unnecessary context explanation - too wordy and ultimately irrelevant to the problem :)



This is not homework - I've written the question like it is to ensure that all the nuances are communicated.



Given the sorted arrays:



 int[] ints =  { 0, 1, 2, 3, 4, 5, 6 };
//this one is important - my current solution fails on this
int[] ints2 = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };


Note due to a clarification asked by a colleague, all that's guaranteed about these arrays is that element[n] will be less than or equal to element[n+1].



Successful operations on these will separate them into two sub arrays L and R (indicated below):



/*ints == */  { 1, 3, 5, 0, 2, 4, 6 }
/*|> L <| |> R <|*/

/*ints2 == */ { 1, 3, 5, 7, 9, 0, 2, 4, 6, 8 }
/*|> L <| |> R <|*/


L contains the integers that are odd and R contains those that are even, whilst retaining the original sort-order of those elements within those subarrays.



The function will NOT resort to re-sorting the elements (a lengthy sort operation will already have been performed in advance) and it won't use a temporary array. I believe that means I'm looking for O(N) complexity and O(1) memory.



The function will be provided with the start and end elements of each sub array - i.e. the caller will know in advance how many items will fall on the left/right sides (possibly by scanning the array in advance for odd/even).



This where my code is at now - I've updated it and commented it from what was in the original post:



public void DivideSubArray(int[] array, int leftStart, int leftCount, 
int rightStart, int rightCount)
{
int currentLeft = leftStart, currentRight = rightStart;
int leftCounter = leftCount;
int temp;
int readahead;
while (leftCounter != 0) {
if ((array[currentLeft] % 2) == 0)
{
//remember the element we swap out
temp = array[currentRight];
//Set as next item on the right. We know this is the next lowest-sorted
//right-hand item because we are iterating through an already-sorted array
array[currentRight++] = array[currentLeft];
// * read ahead to see if there are any further elements to be placed
// * on the left - move them back one by one till there are no more.
readahead = currentLeft + 1;
while ((array[readahead] % 2) != 0)
{
array[currentLeft++] = array[readahead++];
leftCounter--;
}
//Now write the swapped-out item in, but don't increment our currentLeft.
//The next loop will check if the item is in the correct place.
array[currentLeft] = temp;
}
else //this item is already in the correct place
{
currentLeft++;
leftCounter--;
}
}
}


When called as follows:



int numOdd = ints.Count(i => (i % 2) == 1);
DivideSubArray(ints, 0, numOdd, numOdd, ints.Length - numOdd);


It produces the expected array for ints (and many other arrays), but not ints2:



{ 1, 5, 3, 7, 9, 0, 2, 6, 4, 8 }


So it partitions correctly - but swaps 3,5 and 6,4. I understand why: because in the first loop 5 is swapped to the left, then 2 is propagated over because the algorithm says that 5 is odd and should stay. I have a decision tree written out that'll fix it, but having followed it a few loops it infers that the solution is recursive.



I'm struggling to see how to get around this without running more sort operations within the sub array (don't want that), or creating temporary lists/arrays as workspace (might as well stick with my current solution instead).



I feel there must be a simple way to exploit a single 'spare' variable to swap the items - I just can't see it - I'm hoping the SO collective brain will :)





is_null vs ===null [closed]


Possible Duplicate:

What's the difference between is_null($var) and ($var === null)?






Is there any difference between following code:



if(is_null($x)) { ...


and



if($x===null) { ...




gettimeofday/settimeofday for Making a Function Appear to Take No Time

I've got an auxiliary function that does some operations that are pretty costly.



I'm trying to profile the main section of the algorithm, but this auxiliary function gets called a lot within. Consequently, the measured time takes into account the auxillary function's time.



To solve this, I decided to set and restore the time so that the auxillary function appears to be instantaneous. I defined the following macros:



#define TIME_SAVE struct timeval _time_tv; gettimeofday(&_time_tv,NULL);
#define TIME_RESTORE settimeofday(&_time_tv,NULL);


. . . and used them as the first and last lines of the auxiliary function. For some reason, though, the auxiliary function's overhead is still included!



So, I know this is kind of a messy solution, and so I have since moved on, but I'm still curious as to why this idea didn't work.



Can someone please explain why? Ubuntu 10.04 x86_64.



Thanks,
Ian





How to make IE 6 play MPEG-4 HTTP stream?

I have MPEG-4 video stream at http://pool.amursu.ru/video.mpg and I can to watch it using Chrome or Firefox, but Internet Explorer 6 doesn't play it, just attempts to load it forever (I think, it waits for end of file, which, probably, won't ever happen).



I've tried to use Flowplayer and JWplayer, but with no success:



<div id="container">Loading the player...</div>
<script type="text/javascript">
jwplayer("container").setup({
flashplayer: "/jwplayer/player.swf",
width: 800,
height: 450,
levels: [
{
bitrate: 300,
file: "http://pool.amursu.ru/video.mpg",
width: 800
}
],
provider: "http",
"http.startparam":"starttime"
});
</script>


It's available on http://pool.amursu.ru/



The videostream is done by D-Link DCS-2130 webcam and proxied by nginx.



Any ideas to get it working in IE?



P.S> I can set video/mpeg MIME-type for video stream, but it brokes playback in Chrome and doesn't help for IE.



UPD:



For now I've done an unfair solution: found an URL in camera's web interface, from where I can get a single videoframe, proxied it with Nginx, and refresh it every second with javascript. Totally unfair, but works everywhere. http://pool.amursu.ru/





Wednesday, April 25, 2012

Notification Service for Blackberry OS 4.5 application

I am developing an application similar to email application.Whenever new message is received my notification service should indicate change to user by updating icon,also, the notification service should continuosly listen to server for incoming events.



I am developing in os version 4.5.





Facebook batch calls with JSONP

As of 10.04.2012,
There is a short paragraph in the Facebook developer document for 'batch request' entitled: Batch calls with JSONP, which reads:



"The Batch API supports JSONP, just like the rest of the Graph API - 
the JSONP callback function is specified using the 'callback' query string
or form post parameter."


I thought that meant you can also do a batch request using JSONP from Javascript (which will be a GET request, as JSONP works only as a GET request), so I tried that, with adding a 'batch' parameter (containing objects describing requests for batch as in the doc) to the query string.
Response from FB server was:



Only POST is allowed for batch requests


So, questions:

1. What did they mean in that paragraph?

2. Is there a way to do an asynchronous batch request from Javascript?





Looking for a WinForms control that can represent time values

I am looking for a third-party open source or commercial WinForms control that can represent the following values:



Total Duration of Task.

Time Elapsed.

Time Remaining.



Have not been able to find one.





When a subclass is instantiated, is only one object created?

Since many constructors also call the superclass constructor, it seems like one could think that both the subclass and the superclass are instantiated when a subclass is instantiated; i.e. more than one object is created.



Is still just one object created?



Thank you





C Program: newbie trying to pass 2D string array into a function

Programming in C ( with -std=C89), and running into errors trying to pass a character string array into a function.



In main(), I've declared the array as follows:



#define ROWS 501
#define COLS 101
void my_function( char **);
...
char my_array[ROWS][COLS];
...
my_function(my_array);


In my_function, I've declared the array as:



void my_function( char **my_array )
{
...
}


I'm getting this error:



warning: passing argument 1 of 'my_function' from incompatible pointer type,
note: expected 'char **' but argument is of type 'char (*)[101]





PHP echo $_SERVER['PHP_SELF'] with added variable?

Just want to do $_SERVER['PHP_SELF'] as a link with ?logout=1 appended to it.



<a href="<?php echo ''$_SERVER['PHP_SELF']'.logout=1' ?>" id="add"><input type="button" value="LOGOUT" /></a>


gives



Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';' in F:\export\srv\www\vhosts\main\htdocs\php\assign3\m_a2_functions.php on line 90




Redis monitoring info

I'm trying to figure out how to capture the following metrics in redis for monitoring the server. I looked at the INFO command but it does not provide such info.




  1. Operations / sec

  2. a breakdown of commands served, like history of commands served by redis...no of gets, sets, zincrby, zscore etc in the past hour?

  3. Reads per second

  4. writes per second





how to get referrer from a redirected url

I have an url



domain.com/a



which redirects to



domain.com/controller/action/a .



How do I get the referrer (i.e domain.com/a) in my action for domain.com/controller/action/a ?



One option was to add the referring domain as a parameter .



domain.com/controller/action/a?referral=domain.com/a .



Is there a way to get the referrer without passing old referrer as a parameter. Like we would get from **request.referrer**. request.referrer doesn't seem to work with redirected urls.



I am using Ruby on Rails for my development.





Converting searchable PDF to a non-searchable PDF

I have a PDF which is searchable and I need to convert it into a non-searchable one.



I tried using Ghostscript and change it to JPEG and then back to PDF which does the trick but the file size is way too large and not acceptable.



I tried using Ghostscript to convert the PDF to PS first and then PDF which does the trick as well but the quality is not good enough.



gswin32.exe -q -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pswrite -r1000 -sOutputFile=out.ps in.pdf
gswin32.exe -q -dNOPAUSE -dBATCH -dSAFER -dDEVICEWIDTHPOINTS=596 -dDEVICEHEIGHTPOINTS=834 -dPDFSETTINGS=/ebook -sDEVICE=pdfwrite -sOutputFile=out.pdf out.ps


Is there a way to give a good quality to the PDF?



Alternatively is there an easier way to convert a searchable PDF to a non-searchable one?





Loading fixtures in django unit tests

I'm trying to start writing unit tests for django and I'm having some questions about fixtures:



I made a fixture of my whole project db (not certain application) and I want to load it for each test, because it looks like loading only the fixture for certain app won't be enough.



I'd like to have the fixture stored in /proj_folder/fixtures/proj_fixture.json.



I've set the FIXTURE_DIRS = ('/fixtures/',) in my settings.py.
Then in my testcase I'm trying



fixtures = ['proj_fixture.json']


but my fixtures don't load.
How can this be solved?
How to add the place for searching fixtures?
In general, is it ok to load the fixture for the whole test_db for each test in each app (if it's quite small)?
Thanks!





how to differentiate xml from html links in java

I have a list of links, containing links to html and xml pages, how can I extract the xml links from the list? in java



thanks





Send a message to a friend, I wonder Javascript API

Republic of Korea, I am a developer.



Now Facebook and Twitter-based website make.



Javascript API as a message to several friends



I want to spend.



So I consulted the Iframe Javascript API methods or using Facebook page looked as sending.



I wonder.



I use to send messages to friends as a Javascript API that provides a?



I do not know English well. So I used Google translator.



Please understand.



FB.api (path, "post", {

message: msg,

caption: "caption caption",

link: "http://www.naver.com",

description: "Description Description",

picture: "http://sstatic.naver.net/search/img3/h1_naver.gif",

tag: "Tag",

name: "name names",

access_token: accessToken

}, Function (response) {

if (! response | | response.error){

alert ("error");

}

else{

alert (response.id);

}

})




Why does setting the `right` CSS attribute push an element to the left?

I have a very basic page with two elements, an outer green box, and inner blue box. I am confused as to why setting the right attribute on the inner box would move it to the left? Furthermore I am confused as to why right:0 would not align the boxes right edge to the right edge of the parent box? Here is my short example page...



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style type="text/css">
#outer {
background-color : green;
width : 500px;
height : 500px;
}

#inner {
position : relative;
background-color : blue;
height : 400px;
width : 400px;
top : 10px;
right : 20px;
}
</style>
</head>
<body>
<div id="outer">
<div id="inner">


</div>

</div>
</body>
</html>




Google Chrome Uses Wrong Size of Favicon

When I create a a ICO file on the Mac using 'Icon Composer' it allows specifying five images (16x16, 24x24, 32x32, 48x48, 256x256). If I specify a 16x16 and 32x32 Google Chrome (Mac OS X) use the 32x32 image as the icon that appears next to the name on the tabs and under the favourites (it is resized to 16x16). This causes the icon to look blurry.



Am I creating my favicon.ico correctly? Do I need to do anything else to tell the browser to use the 16x16 image? I currently have:



<head>
<link rel="shortcut icon" href="/favicon.ico" />
</head>




Saving Images To A Plist With NSUserDefaults

I have an app that behaves like a photo gallery. I'm implementing the ability for the user to delete the photos, by placing an invisible button over each UIImageView, and calling removeObject when they tap on the button. This code is working great, but its dependent upon tags. I need to tag every UIImageView / UIButton in interface builder in order for this to work. So, I'm now trying to save the images. I'm in a pretty strange predicament, if I use NSUserDefaults to save the pictures (I'm storing them in an array), I can delete the images perfectly, but I cant get them to save/load. If I use NSData to save the images in the array, I can save/load the images, but I cant delete them since my current code depends on the UIImageViews tags, which I can't use with NSData.



So I'm totally lost on what to do right now. I'm very, very new to programming and am shocked that I even made it this far. Any help or advice on what or how to edit my code to make this work is much appreciated, thanks!



Here is my entire file just for reference. This is how I grab the images, and how I'm attempting to save / load them:



- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {
if (imageView.image == nil) {
imageView.image = img;

[self.array addObject:imageView.image];

[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;

}

if (imageView2.image == nil) {
imageView2.image = img;

[self.array addObject:imageView2.image];

[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;
}

if (imageView3.image == nil) {
imageView3.image = img;

[self.array addObject:imageView3.image];

[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;
}
- (void)applicationDidEnterBackground:(UIApplication*)application {
NSLog(@"Image on didenterbackground: %@", imageView);

[self.array addObject:imageView.image];
[self.array addObject:imageView2.image];
[self.array addObject:imageView3.image];

[self.user setObject:self.array forKey:@"images"];
[user synchronize];

}
- (void)viewDidLoad
{
self.user = [NSUserDefaults standardUserDefaults];
NSLog(@"It is %@", self.user);
self.array = [[self.user objectForKey:@"images"]mutableCopy];
imageView.image = [[self.array objectAtIndex:0] copy];
imageView2.image = [[self.array objectAtIndex:1] copy];
imageView3.image = [[self.array objectAtIndex:2] copy];


UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:app];
}


Here is how I delete the image when the user taps on the hidden button over the UIImageView:



- (IBAction)deleteButtonPressed:(id)sender {
NSLog(@"Sender is %@", sender);
UIAlertView *deleteAlertView = [[UIAlertView alloc] initWithTitle:@"Delete"
message:@"Are you sure you want to delete this photo?"
delegate:self
cancelButtonTitle:@"No"
otherButtonTitles:@"Yes", nil];
[deleteAlertView show];

int imageIndex = ((UIButton *)sender).tag;
deleteAlertView.tag = imageIndex;
}

- (UIImageView *)viewForTag:(NSInteger)tag {
UIImageView *found = nil;
for (UIImageView *view in self.array) {
if (tag == view.tag) {
found = view;
break;
}
}
return found;
}

- (void)alertView: (UIAlertView *) alertView
clickedButtonAtIndex: (NSInteger) buttonIndex
{


if (buttonIndex != [alertView cancelButtonIndex]) {
NSLog(@"User Clicked Yes. Deleting index %d of %d", alertView.tag, [array count]);
NSLog(@"The tag is %i", alertView.tag);

UIImageView *view = [self viewForTag:alertView.tag];
if (view) {
[self.array removeObject:view];
}

NSLog(@"After deleting item, array count = %d", [array count]);
NSLog(@"Returned view is :%@, in view: %@", [self.view viewWithTag:alertView.tag], self.view);
((UIImageView *)[self.view viewWithTag:alertView.tag]).image =nil;
}

[self.user setObject:self.array forKey:@"images"];
}




running OS on bochs returned error

I'm working on an OS programming project called pintos. It is run on bochs following the command pintos run nameOfProcess



And here's the error message I get



Writing command line to /tmp/eKW3NMXoGT.dsk...
squish-pty bochs -q
========================================================================
Bochs x86 Emulator 2.5.1.svn
Built from SVN snapshot, after release 2.5.1
Compiled on Apr 6 2012 at 19:37:19
========================================================================
00000000000i[ ] reading configuration from bochsrc.txt
00000000000i[ ] installing x module as the Bochs GUI
00000000000i[ ] using log file bochsout.txt
Next at t=0
Writing command line to /tmp/eKW3NMXoGT.dsk...
squish-pty bochs -q
========================================================================
Bochs x86 Emulator 2.5.1.svn
Built from SVN snapshot, after release 2.5.1
Compiled on Apr 6 2012 at 19:37:19
========================================================================
00000000000i[ ] reading configuration from bochsrc.txt
00000000000i[ ] installing x module as the Bochs GUI
00000000000i[ ] using log file bochsout.txt
Next at t=0
(0) [0x00000000fffffff0] f000:fff0 (unk. ctxt): (invalid) ; ffff
<bochs:1> fgets() returned ERROR.
debugger interrupt request was 0
(0).[0] [0x00000000fffffff0] f000:fff0 (unk. ctxt): (invalid) ; ffff
(0) [0x00000000fffffff0] f000:fff0 (unk. ctxt): (invalid) ; ffff
<bochs:1> fgets() returned ERROR.
debugger interrupt request was 0
(0).[0] [0x00000000fffffff0] f000:fff0 (unk. ctxt): (invalid) ; ffff


Also my bochsrc.txt



romimage: file=$BXSHARE/BIOS-bochs-latest, address=0xe0000  
vgaromimage: file=$BXSHARE/VGABIOS-lgpl-latest
boot: disk
cpu: ips=1000000
megs: 4
log: bochsout.txt
panic: action=fatal
clock: sync=none, time0=0
ata0-master: type=disk, path=/tmp/eKW3NMXoGT.dsk, mode=flat, cylinders=1, heads=16, spt=63, translation=none
com1: enabled=1, mode=term, dev=/dev/stdout


Bochs was built from source with extra configurations on my Ubuntu 11.04





Struct.Error, Must Be a Bytes Object?

I am attempting to execute the code:



    values = (1, 'ab', 2.7)    
s.struct.Struct('I 2s f')
packed = s.pack(*values)


But I keep getting the error:



    Traceback (most recent call last):
File "<stdin>", line 1, in <module>
struct.error: argument for 's' must be a bytes object


Why?How do I fix this?





Java / Eclipse (WindowBuilder plugin) - how do I effectively use Swing Actionlisteners?

My question is specific to Eclipse and the Swing WindowBuilder plugin.



To make simple Swing apps I normally create a class and extend a JFrame. I make my Swing components private class variables. This allows me to add an Actionlisteners and access the swing components in actionPerformed(), like this:



public class MyClass() extends JFrame implements ActionListener {
private JButton btnClickMe = new JButton("Click me");

public MyClass() {
super("title");
this.setLayout(null);
btnClickMe.setBounds(1,1,100,100);
this.add(btnClickMe);
btnClickMe.addActionListener(this);
this.setVisible(true);
}

public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == btnClickMe) { // do something }
}

public static void main(String[] args) {
new MyClass();
}
}


By default the WindowBuilder plugin create Swing component variables I guess in what would be considered the constructor (public MyClass()), rather than private class variables. As a result due to scope I am not able to use ActionListeners the way I am used to since the Swing variables are not visible to actionPerformed().



Can anyone advise how this can be overcome?





How does the textbox + button actually do the searching in asp.net?

I was just curious as to how the textbox + button search actually performs the search to fill up my gridviews, because I couldn't see anywhere that causes the databounds or anything. Is it a post-back thing? How does it work?! o.o



<asp:TextBox ID="SearchBox" runat="server"></asp:TextBox>
<input id="Submit1" type="submit" value="Search" />


Thanks heaps :)





I want to get the current position for ruby script only

Ruby script only, please tell me the best practice to get the current position of latitude, longitude.





How do Java method annotations work in conjunction with method overriding?

I have a parent class Parent and a child class Child, defined thus:



class Parent {
@MyAnnotation("hello")
void foo() {
// implementation irrelevant
}
}
class Child {
@Override
foo() {
// implementation irrelevant
}
}


If I obtain a Method reference to Child::foo, will childFoo.getAnnotation(MyAnnotation.class) give me @MyAnnotation? Or will it be null?



I'm interested more generally in how or whether annotation works with Java inheritance.





How do I clear the console in Objective-C

I'm making a console-based application in Objective-C which relies on being able to clear the console periodically. How can this be done? All I've seen on SO and Google were ways to have the developer clear the console with X-Code, but that will not do.



One solution I found on Yahoo! Answers told me to do the following, but it does not run due to being unable to find a file:



NSTask *task;
task = [[NSTask alloc]init];
[task setLaunchPath: @"/bin/bash"];

NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"clear", nil];
[task setArguments: arguments];

[task launch];
[task waitUntilExit];




How to use an API level 8 class when possible, and do nothing otherwise

I have a custom view in my Android App that uses a ScaleGestureDetector.SimpleOnScaleGestureListener to detect when the user wants to scale the view via a 2 finger pinch in or out. This works great until I tried testing on an Android 2.1 device, on which it crashes immediately because it cannot find the class.



I'd like to support the pinch zoom on 2.2+ and default to no pinch zoom <2.1. The problem is I can't declare my:



private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
{
@Override
public boolean onScale(ScaleGestureDetector detector)
{
MyGameActivity.mScaleFactor *= detector.getScaleFactor();

// Don't let the object get too small or too large.
MyGameActivity.mScaleFactor = Math.max(0.1f, Math.min(MyGameActivity.mScaleFactor, 1.0f));

invalidate();
return true;
}
}


at all on android <2.1. Is there a clever way to get around this using java reflection? I know how to test if a method exists via reflection, but can I test if a class exists? How can I have my



private ScaleGestureDetector mScaleDetector;


declared at the top of my class if the API can't even see the ScaleGestureDetector class?



It seems like I should be able to declare some sort of inner interface like:



public interface CustomScaleDetector
{
public void onScale(Object o);
}


And then somehow...try to extend ScaleGestureDetector depending on if reflection tells you that the class is accessible...



But I'm not really sure where to go from there. Any guidance or example code would be appreciated, let me know if it isn't clear what I'm asking.





Search for a packages by a particular author

Sometimes I get accustomed to a particular R package's design and want to search CRAN for all packages by that author (let's use Hadley Wickham for instance). How can I do such a search (I'd like to use R but this doesn't have to be the mode of search).





Using data from C# DataReceived thread in a parent class (NO UI, can't Invoke)

I have a class that needs to have properties updated with data from the C# serial DataReceived event.



I'm not trying to update a UI, but the only references I find about using the results of the DataReceived event (which runs on a different thread) say to use .Invoke to get the data into a UI control. My class is not associated with a UI so .Invoke is not available.



When the handler tries to change a property in the class, I get the dreaded error: "The calling thread cannot access this object because a different thread owns it."



What is process for getting the results into the parent thread?





Coding a function to copy a linked-list [C++]

I need to implement an auxilliary function, named copyList, having one parameter, a pointer to a ListNode. This function needs to return a pointer to the first node of a copy of original linked list. So, in other words, I need to code a function in C++ that takes a header node of a linked list and copies that entire linked list, returning a pointer to the new header node. I need help implementing this function and this is what I have right now.



Listnode *SortedList::copyList(Listnode *L) {

Listnode *current = L; //holds the current node

Listnode *copy = new Listnode;
copy->next = NULL;

//traverses the list
while (current != NULL) {
*(copy->student) = *(current->student);
*(copy->next) = *(current->next);

copy = copy->next;
current = current->next;
}
return copy;
}


Also, this is the Listnode structure I am working with:



struct Listnode {    
Student *student;
Listnode *next;
};


Note: another factor I am running into with this function is the idea of returning a pointer to a local variable.





How to get good performance when writing a list of integers from 1 to 10 million to a file?

question



I want a program that will write a sequence like,



1
...
10000000


to a file. What's the simplest code one can write, and get decent performance? My intuition is that there is some lack-of-buffering problem. My C code runs at 100 MB/s, whereas by reference the Linux command line utility dd runs at 9 GB/s 3 GB/s (sorry for the imprecision, see comments -- I'm more interested in the big picture orders-of-magnitude though).



One would think this would be a solved problem by now ... i.e. any modern compiler would make it immediate to write such programs that perform reasonably well ...



C code



#include <stdio.h>

int main(int argc, char **argv) {
int len = 10000000;
for (int a = 1; a <= len; a++) {
printf ("%d\n", a);
}
return 0;
}


I'm compiling with clang -O3. A performance skeleton which calls putchar('\n') 8 times gets comparable performance.



Haskell code



A naiive Haskell implementation runs at 13 MiB/sec, compiling with ghc -O2 -optc-O3 -optc-ffast-math -fllvm -fforce-recomp -funbox-strict-fields. (I haven't recompiled my libraries with -fllvm, perhaps I need to do that.) Code:



import Control.Monad
main = forM [1..10000000 :: Int] $ \j -> putStrLn (show j)


My best stab with Haskell runs even slower, at 17 MiB/sec. The problem is I can't find a good way to convert Vector's into ByteString's (perhaps there's a solution using iteratees?).



import qualified Data.Vector.Unboxed as V
import Data.Vector.Unboxed (Vector, Unbox, (!))

writeVector :: (Unbox a, Show a) => Vector a -> IO ()
writeVector v = V.mapM_ (System.IO.putStrLn . show) v

main = writeVector (V.generate 10000000 id)


It seems that writing ByteString's is fast, as demonstrated by this code, writing an equivalent number of characters,



import Data.ByteString.Char8 as B
main = B.putStrLn (B.replicate 76000000 '\n')


This gets 1.3 GB/s, which isn't as fast as dd, but obviously much better.





drawString with Rectangle border

I want to draw string using Graphics with Rectangle border outside the string.



This is what I already do:



public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
FontMetrics fontMetrics = g2d.getFontMetrics();
String str = "aString Test";

int width = fontMetrics.stringWidth(str);
int height = fontMetrics.getHeight();

int x = 100;
int y = 100;

// Draw String
g2d.drawString(str, x, y);
// Draw Rectangle Border based on the string length & width
g2d.drawRect(x - 2, y - height + 2, width + 4, height);
}


My problem is, I want to draw string with new line ("\n") with Rectangle border outside:



This is the code for the new line:



public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
FontMetrics fontMetrics = g2d.getFontMetrics();
String str = "aString\nTest";

int width = fontMetrics.stringWidth(str);
int height = fontMetrics.getHeight();

int x = 100;
int y = 100;

// Drawing string per line
for (String line : str.split("\n")) {
g2d.drawString(line, x, y += g.getFontMetrics().getHeight());
}
}


Can anyone help me for this problem? I appreciate your help & suggestion...





Database design advice in Rails, The Pizza, Topping and Order

Yes, its another database question with the pizza analogy.
The ones I've seen don't seem to click just right, so here goes.



I need to be able to order multiple pizzas with any number of toppings in a single order.
Its a basic shopping cart pattern, but the toppings are making it difficult to implement.



The base models are,



class Pizza < ActiveRecord::Base
has_and_belongs_to_many :orders
has_and_belongs_to_many :toppings
end

class Topping < ActiveRecord::Base
has_and_belongs_to_many :pizzas
end


Pizza and Topping tables serve as the holder for the information of pizza and topping types that can be ordered.



class OrdersPizzas < ActiveRecord::Base
belongs_to :order
belongs_to :pizza
end

class PizzasToppings < ActiveRecord::Base
belongs_to :topping
belongs_to :pizza
end

class Order < ActiveRecord::Base
has_and_belongs_to_many :pizzas
end


[Added]



Some clarification, the database design is intended for a shopping app, so being able to setup a "menu" by an admin, and users being able to see the menu, and order from it is imperative.



The operation of this goes in two steps, first you need to make a menu by creating the Pizzas and toppings, and associating them, not all pizzas can have all the toppings.




A Cheese Pizza can have extra olives, and extra cheese as toppings



A Peperoni Pizza can have only extra cheese for toppings




Step two is actually placing the orders according to the entered data, thus all the many to manys.



Now the question is, after entering the data above, I want to place an order




Peperoni Pizza with extra cheese



Cheeze Pizza with extra olives




in a single order, how should it be designed?



All I can think of is to add a



class OrdersPizzasToppings < ActiveRecord::Base
belongs_to :orders_pizzas
belongs_to :topping
end


so I can distinguish which pizza has the toppings, but that does not look like the right way to go.





MVC SQL cyclical cascade paths

I'm building a simple code-first MVC 3 blog like application. My model has three tables, user, comment, and tutorial. The comment table has a FK for both user and tutorial. Tutorial has also a foreign key for user.



When I run the program I get the following error:



Introducing FOREIGN KEY constraint 'FK_Comments_Users_UserID' on table 'Comments' 
may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON
UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.


It seems like the problem is being caused by something called cascading deletes. Microsoft's solution to this is to have better DB design, http://support.microsoft.com/kb/321843. But this DB seems to be about as simple as you can get.



I've found a few other posts (Entity Framework Code first - FOREIGN KEY constraint problem) which seem to address this issue by adding a the following code in my db context class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{



 modelBuilder.Entity<User>()
.HasMany(u => u.Comments)
.HasRequired(c => c.User)
.HasForeignKey(c => c.UserId)
.WillCascadeOnDelete(false);
}


Unfortunately, Visual Studio gets mad at the syntax at '.HasRequired' The actual error is "Error 1 'System.Data.Entity.ModelConfiguration.Configuration.ManyNavigationPropertyConfiguration' does not contain a definition for 'HasRequired' and no extension method 'HasRequired' accepting a first argument of type 'System.Data.Entity.ModelConfiguration.Configuration.ManyNavigationPropertyConfiguration' could be found (are you missing a using directive or an assembly reference?)"



It seems like there is something simple here that I am missing. How can I restructure my database better or how can I solve this cyclical redundancy problem?





Tuesday, April 24, 2012

Ardor3D transparent quad

I am using Ardor3D for a 3D application in Java. I can draw a quad to the screen with a texture mapped to it. Part of the texture image is transparent, and the quad background shows through there.



How do you make the quad itself transparent, so the rendered scene will show through?





Writing files to Dropbox account from GAE

I am trying to create files in a Dropbox.com folder from a GAE application.
I have done all the steps the register a Dropbox application and installed the Python SDK from Dropbox locally on my development machine. (see dropbox.com API).
It all works perfectly when I use the cli_client.py test script in the dropbox SDK on my local machine to access dropbox - can 'put' files etc.



I now want to start working in GAE environment, so things get a bit tricky.
Some help would be useful.



For those familiar with the Dropbox API code, I had the following issues thus far:



Issue 1



The rest.py Dropbox API module uses pkg_resources to get the certs installed in site-packages of a local machine installation.
I replaced



TRUSTED_CERT_FILE = pkg_resources.resource_filename(__name__, 'trusted-certs.crt')


with



TRUSTED_CERT_FILE = file('trusted-certs.crt')


and placed the cert file in my GAE application directory. Perhaps this is not quite right; see my authentication error code below.



Issue 2



The session.py Dropbox API module uses oauth module, so I changed the include to appengine oauth.



But raised an exception that GAE's oauth does not have OAuthConsumer method used by the Dropbox session.py module. So i downloaded oauth 1.0 and added to my application an now import this instead of GAE oauth.



Issue 3



GAE ssl module does not seem to have CERT_REQUIRED property.



This is a constant, so I changed



self.cert_reqs = ssl.CERT_REQUIRED


to



self.cert_reqs = 2


This is used when calling



ssl.wrap_socket(sock, cert_reqs=self.cert_reqs, ca_certs=self.ca_certs)


Authentication Error



But I still can't connect to Dropbox:



Status: 401
Reason: Unauthorized
Body: {"error": "Authentication failed"}
Headers: [('date', 'Sun, 19 Feb 2012 15:11:12 GMT'), ('transfer-encoding', 'chunked'), ('connection', 'keep-alive'), ('content-type', 'application/json'), ('server', 'dbws')]




MySQLdb not running on Mac 10.7

I am trying to install MySQL-Python (MySQLdb) locally on my Mac and I am having trouble. I have been working on this for HOURS and I continue to get this error:



>>> import MySQLdb
/Library/Python/2.7/site-packages/MySQL_python-1.2.3-py2.7-macosx-10.7-intel.egg/_mysql.py:3: UserWarning: Module _mysql was already imported from /Library/Python/2.7/site-packages/MySQL_python-1.2.3-py2.7-macosx-10.7-intel.egg/_mysql.pyc, but /Users/dp/Code/MySQL-python-1.2.3 is being added to sys.path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "MySQLdb/__init__.py", line 19, in <module>
import _mysql
File "build/bdist.macosx-10.7-intel/egg/_mysql.py", line 7, in <module>
File "build/bdist.macosx-10.7-intel/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/dp/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.7-intel.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
Referenced from: /Users/dp/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.7-intel.egg-tmp/_mysql.so
Reason: image not found
>>>


I am trying to set up a python 2.7/Django/MySQL development environment and keep running into this problem. I have a feeling this could a problem with my .bash_profiles PATH so I am also including that below:



export PATH="/usr/local/mysql/bin:$PATH"


Thank you!!!



dp





Strategy for Dynamic Tags in MongoDB

On Facebook statues, you can start typing an @ and tag a user in a status. This question is not about the frontend, but rather how to store the data for that feature. What is the best way to achieve this functionality in a generic way for representing any mongodb entity in a string in a dynamic way. The goal being if the entity changes, it representation in the stored string also changes. For example one idea I had was this:



Post: {
_id: "48ajsdlfhsdjfkjsljsd"
name: "Post One",
text: "@user is the best for liking @thing, and @thing"
tags: [user:1234, thing:456, thing:789]
}


So I would load this post, then look at the tags, load the models for each tag type and id, then rewrite the string to be: "Chris is the best for liking StackOverflow, and Mongo". This seems inefficient, any better ideas?





Is it right to say that not all superclass is the high-level component of the subclass?

A "High-Level" component is a class with behavior defined in terms of other "low level" components. Example of this is Bulb class needs Socket class to implements its LightOn() behavior.



Not all superclass is the high-level component and not all subclass is the low-level component. Because of the following examples.



Template method pattern from head first design pattern.



public abstract class CaffeineBeverage {

final void prepareRecipe() {
boilWater();
brew();
pourInCup();
addCondiments();
}

abstract void brew();

abstract void addCondiments();

void boilWater() {
System.out.println("Boiling water");
}

void pourInCup() {
System.out.println("Pouring int cup");
}
}

public class Coffee extends CaffeineBeverage {

public void brew() {
System.out.println("Dripping Coffee through filter");
}

public void addCondiments() {
System.out.println("Adding Sugar and Milk");
}
}


In this example CaffeineBeverage class has a behavior prepareRecipe(). This behavior needs subclass implementation of brew() and addCondiments().



so... this means here CaffeineBeverage (superclass) is the high-level component and Coffee (subclass) is the low-level component.



public class superClass {
public go() {
//super class implementation
}
}

public class subClass extends superClass {
public go() {
//sub class implementation
}
}


In this case superClass didnt need subclass to implement its go() method.



Even if a class has abstract method that needs the subclass to implement it DOESNT mean super class is the high level component. See example below.



public abstract class superClass {
public abstract go();
}

public class subClass extends superClass {
public go() {
//subclass implementation;
}
}

main() {
superClass s = new subClass();
s.go();
}


Here s is not superClass object... s here is the subClass object.





Byte to string for hash function?

How can I convert passwordHash to string?



    protected RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();

public byte[] GenerateSalt()
{
byte[] salt = new byte[10];
random.GetNonZeroBytes(salt);
return salt;
}

public static byte[] Hash(string value, byte[] salt)
{
return Hash(Encoding.UTF8.GetBytes(value), salt);
}

public static byte[] Hash(byte[] value, byte[] salt)
{
byte[] saltedValue = value.Concat(salt).ToArray();

return new SHA256Managed().ComputeHash(saltedValue);
}

public void AddStudent(Student student)
{
student.StudentID = (++eCount).ToString();
byte[] passwordHash = Hash(student.Password, GenerateSalt());
student.Password = passwordHash; //this line?
student.TimeAdded = DateTime.Now;
students.Add(student);
}


If I try:



    public void AddStudent(Student student)
{
student.StudentID = (++eCount).ToString();
byte[] passwordHash = Hash(student.Password, GenerateSalt());
student.Password = Convert.ToString(passwordHash); //this line?
student.TimeAdded = DateTime.Now;
students.Add(student);
}


When I GET my Student collection the password field will say System.Byte[] where as I want to get the hashed/salted password back?





Getting error with simple select statement on web2py's 'image blog'

For my project, I need to connect to multiple databases and get information from them. I didn't think this would be a problem with web2py, but it was. I thought maybe I need to rebuild the db from scratch, but still had problems. Finally, I went through the introductory 'images' tutorial and changed it to use an alternate mysql database. I still got the same errors, below is the code:



db.py



db = DAL("mysql://root:@localhost/web2py")
images_db = DAL("mysql://root:@localhost/images_test")


images_db.define_table('image',
Field('title', unique=True),
Field('file', 'upload'),
format = '%(title)s')


images_db.define_table('comment',
Field('image_id', images_db.image),
Field('author'),
Field('email'),
Field('body', 'text'))


Then I went to the admin page for 'images' and clicked the 'shell' link under 'controllers' and did the following: (after I went to the index page to generate the 'images':



Shell:



In [1] : print db(images_db.image).select()
Traceback (most recent call last):
File "/home/cody/Downloads/web2py/gluon/contrib/shell.py", line 233, in run
exec compiled in statement_module.__dict__
File "<string>", line 1, in <module>
File "/home/cody/Downloads/web2py/gluon/dal.py", line 7577, in select
fields = adapter.expand_all(fields, adapter.tables(self.query))
File "/home/cody/Downloads/web2py/gluon/dal.py", line 1172, in expand_all
for field in self.db[table]:
File "/home/cody/Downloads/web2py/gluon/dal.py", line 6337, in __getitem__
return dict.__getitem__(self, str(key))
KeyError: 'image'


In [2] : print images_db.has_key('image')
True


In [3] : print images_db
<DAL {'_migrate_enabled': True, '_lastsql': "SET sql_mode='NO_BACKSLASH_ESCAPES';", '_db_codec': 'UTF-8', '_timings': [('SET FOREIGN_KEY_CHECKS=1;', 0.00017380714416503906), ("SET sql_mode='NO_BACKSLASH_ESCAPES';", 0.00016808509826660156)], '_fake_migrate': False, '_dbname': 'mysql', '_request_tenant': 'request_tenant', '_adapter': <gluon.dal.MySQLAdapter object at 0x2b84750>, '_tables': ['image', 'comment'], '_pending_references': {}, '_fake_migrate_all': False, 'check_reserved': None, '_uri': 'mysql://root:@localhost/images_test', 'comment': <Table {'body': <gluon.dal.Field object at 0x2b844d0>, 'ALL': <gluon.dal.SQLALL object at 0x2b84090>, '_fields': ['id', 'image_id', 'author', 'email', 'body'], '_sequence_name': 'comment_sequence', '_plural': 'Comments', 'author': <gluon.dal.Field object at 0x2b84e10>, '_referenced_by': [], '_format': None, '_db': <DAL {...}>, '_dbt': 'applications/images/databases/e1e448013737cddc822e303fe20f8bec_comment.table', 'email': <gluon.dal.Field object at 0x2b84490>, '_trigger_name': 'comment_sequence', 'image_id': <gluon.dal.Field object at 0x2b84050>, '_actual': True, '_singular': 'Comment', '_tablename': 'comment', '_common_filter': None, 'virtualfields': [], '_id': <gluon.dal.Field object at 0x2b84110>, 'id': <gluon.dal.Field object at 0x2b84110>, '_loggername': 'applications/images/databases/sql.log'}>, 'image': <Table {'ALL': <gluon.dal.SQLALL object at 0x2b84850>, '_fields': ['id', 'title', 'file'], '_sequence_name': 'image_sequence', 'file': <gluon.dal.Field object at 0x2b847d0>, '_plural': 'Images', 'title': <gluon.dal.Field object at 0x2b84610>, '_referenced_by': [('comment', 'image_id')], '_format': '%(title)s', '_db': <DAL {...}>, '_dbt': 'applications/images/databases/e1e448013737cddc822e303fe20f8bec_image.table', '_trigger_name': 'image_sequence', '_loggername': 'applications/images/databases/sql.log', '_actual': True, '_tablename': 'image', '_common_filter': None, 'virtualfields': [], '_id': <gluon.dal.Field object at 0x2b848d0>, 'id': <gluon.dal.Field object at 0x2b848d0>, '_singular': 'Image'}>, '_referee_name': '%(table)s', '_migrate': True, '_pool_size': 0, '_common_fields': [], '_uri_hash': 'e1e448013737cddc822e303fe20f8bec'}>


Now I don't quite understand why I am getting errors here, everything appears to be in order. I thought web2py supported multiple databases? Am I doing it wrong? The appadmin works fine, perhaps I'll edit it and get it to raise an error with the code it's generating... any help would be appreciated.




  • Cody



UPDATE:



I just tried this:



MODELS/DB.PY



db = DAL("mysql://root:@localhost/web2py")

images_db = DAL("mysql://root:@localhost/images_test")


images_db.define_table('image',
Field('title', unique=True),
Field('file', 'upload'),
format = '%(title)s')


images_db.define_table('comment',
Field('image_id', images_db.image),
Field('author'),
Field('email'),
Field('body', 'text'))


CONTROLLERS/DEFAULT.PY



def index():
"""
example action using the internationalization operator T and flash
rendered by views/default/index.html or views/generic.html
"""
if images_db.has_key('image'):
rows = db(images_db.image).select()
else:
rows = 'nope'
#rows = dir(images_db)
return dict(rows=rows)


VIEWS/DEFAULT/INDEX.HTML



{{left_sidebar_enabled,right_sidebar_enabled=False,True}}
{{extend 'layout.html'}}


these are the rows:
{{=rows }}


Again, very confused by all of this. Appreciate any help.





Meteor.http method is undefined on server?

So, I'm trying to write a method that makes an http call. When I run the method, I get the following error:



Exception while invoking method 'upload' TypeError: Cannot call method 'call' of undefined



Here is what the code looks like:



Client:



console.log(Meteor.call('upload', f, content));


Server:



Meteor.methods({
upload: function(file, content) {
this.unblock();
Meteor.http.call("PUT", "http://blah");
}
});




Close window in Tkinter message box

link text



How to handle the "End Now" error in the below code:



import Tkinter
from Tkconstants import *
import tkMessageBox

tk = Tkinter.Tk()

class MyApp:

def __init__(self,parent):

self.myparent = parent

self.frame = Tkinter.Frame(tk,relief=RIDGE,borderwidth=2)
self.frame.pack()

self.message = Tkinter.Message(tk,text="Symbol Disolay")

label=Tkinter.Label(self.frame,text="Is Symbol Displayed")
label.pack()

self.button1=Tkinter.Button(self.frame,text="YES")
self.button1.pack(side=BOTTOM)
self.button1.bind("<Button-1>", self.button1Click)

self.button2=Tkinter.Button(self.frame,text="NO")
self.button2.pack()
self.button2.bind("<Button-1>", self.button2Click)

self.myparent.protocol("WM_DELETE_WINDOW", self.handler)


def button1Click(self, event):
print "pressed yes"

def button2Click(self, event):
print "pressed no"


def handler(self):
if tkMessageBox.askokcancel("Quit?", "Are you sure you want to quit?"):
self.myparent.quit()


myapp = MyApp(tk)
tk.mainloop()




Why do I get this exception? {An item with the same key has already been added."})

Aknittel

NewSellerID is the result of a lookup on tblSellers. These tables (tblSellerListings and tblSellers) are not "officially" joined with a foreign key relationship, either in the model or in the database, but I want some referential integrity maintained for the future. So my issue remains. Why do I get the exception ({"An item with the same key has already been added."}) with this code, if I don't begin each iteration of the foreach loop with a new ObjectContext and end it with SaveChanges, which I think will affect performance. Also, could you tell me why ORCSolutionsDataService.tblSellerListings (An ADO.NET DataServices/WCF object is not IDisposable, like LINQ to Entities??



==============================================



// Add listings to previous seller
int NewSellerID = 0;

// Look up existing Seller key using SellerUniqueEBAYID
var qryCurrentSeller = from s in service.tblSellers
where s.SellerEBAYUserID == SellerUserID
select s;

foreach (var s in qryCurrentSeller)
NewSellerID = s.SellerID;

// Save the selected listings for this seller

foreach (DataGridViewRow dgr in dgvRows)
{

ORCSolutionsDataService.tblSellerListings NewSellerListing = new ORCSolutionsDataService.tblSellerListings();
NewSellerListing.ItemID = dgr.Cells["txtSellerItemID"].Value.ToString();
NewSellerListing.Title = dgr.Cells["txtSellerItemTitle"].Value.ToString();
NewSellerListing.CurrentPrice = Convert.ToDecimal(dgr.Cells["txtSellerItemPrice"].Value);
NewSellerListing.QuantitySold = Convert.ToInt32(dgr.Cells["txtSellerItemSold"].Value);
NewSellerListing.EndTime = Convert.ToDateTime(dgr.Cells["txtSellerItemEnds"].Value);
NewSellerListing.CategoryName = dgr.Cells["txtSellerItemCategory"].Value.ToString();
NewSellerListing.ExtendedPrice = Convert.ToDecimal(dgr.Cells["txtExtendedReceipts"].Value);
NewSellerListing.RetrievedDtime = Convert.ToDateTime(dtSellerDataRetrieved.ToString());
NewSellerListing.SellerID = NewSellerID;

service.AddTotblSellerListings(NewSellerListing);

}

service.SaveChanges();


}



catch (Exception ex)
{
MessageBox.Show("Unable to add a new case. Exception: " + ex.Message);



}





Weka: ADTree and LADTree Illegal Options Error

Before I start my question, I should preface it by saying that the main Weka site is down, and I can't access its support pages.



I'm trying to call Weka classifiers from some automation software and I'm running into a problem - I'm calling it with options I know to be legal from the explorer GUI, but I'm getting an exception telling me that those options are illegal:



Explorer classifier path:



weka.classifiers.trees.ADTree -B 10 -E -3


My code:



classifier = trainWekaClassifier(matlab2weka('training', featurelabels, train), trees.ADTree', {strcat('-B 10 -E -3')});


The error is:



??? Java exception occurred:
java.lang.Exception: Illegal options: -B 10 -E -3

at weka.core.Utils.checkForRemainingOptions(Utils.java:482)

at weka.classifiers.trees.ADTree.setOptions(ADTree.java:1144)


Error in ==> trainWekaClassifier at 40
wekaClassifier.setOptions(options);

Error in ==> classifier_search at 223
classifier = trainWekaClassifier(matlab2weka('training', featurelabels,
train), 'trees.ADTree', {strcat('-B 10 -E -3')});


Any help you can offer would be greatly appreciated. Thank you!