Tuesday, April 24, 2012

Wicket AbstractAjaxTimerBehavior and performance

I'm using AbstractAjaxWicketBehavior in my Wicket application and it seems to have a descending performance over time when more AJAX calls appear. When a page is refreshed without AJAX, the performance is fine again. I would like to know if this is a normal thing or can be a memory leak of some kind present? I can't simply attach the code as it's spread over more classes and it would require too much effort to understand, but in short I want to do this:




  1. create and start the timer

  2. repeat some code 10x

  3. stop the timer

  4. set some values to attributes

  5. ajax refresh (causes show/hide of some components)



and do the same again (hypotetically infinite times).



Every repetition of this flow is slower even though I use constant updating interval of 100ms.



As the timer is a behavior and does not allow to be restarted or reused, it is created every time as a new instance and attached to the Form component.



The timer looks like this:



static int count = 0
new AbstractAjaxTimerBehavior(Duration.milliseconds(100)) {
// do some code
count++
if(count == 10) {
stop();
// do some code
}
}


This behavior is attached to a Form inside a Panel and upon a click on an AjaxLink the Form is refreshed (added to AjaxRequestTarget). Every time I remove the old timer from the Form component before adding the new behavior.



Everything works fine, but every repetition of this procedure runs slower (The first one is perfect, the second one is also around 100ms, but then it gets slower (after 10 or 15 repetitions, the refresh interval is about 1 second) and all other AJAX calls in the app also go significantly slower), so I suspect there is a memory leak... any obvious reasons? Or any ways how to make a wicket timer better for my purpose? Any advice appreciated. Thanks.





jQuery: $(element).text() doesn't work

Why isn't this working? I've searched Stackoverflow and jQuery API and it should work. Instead I get an empty string :(



function a(){
var div=document.createElement("div");
div.innerHTML='<a class="aClass" href="javascript:showMyText(this)">Link Text</a>';

var parent_div=document.getElementById('dinamicni_div');
parent_div.appendChild(div);
}

function showMyText(link){
var txt=$(link).text();
alert(txt);
}




Transition between 2 movies using a MPMoviePlayerController

I'm trying to make a smooth cross fade between 2 movies in my iPad App. On a button tap the visuals randomize & the movie which is playing fades to the next movie.



Since 2 movies cannot be played simultaneously (from the docs) a straight-forward cross-fade isn't possible. To get around this I use a still image of the initial frame of the new movie (which is to be faded in). I used two players to handle the interchange of movies.



The original movie is paused, Then I transition to the image. Now I add my 2nd movie (with alpha = 0.0) & then transition so that its alpha = 1. I then play the new movie. This all works ok except for a noticeable darkening as the new movie transitions in over the image.



I tested it without the still image & the darkening doesn't seem to occur during said transition.



My code for the switch is below (first half of the if-statement). It looks pretty strange ,looking over it, but it's the method that brought me closest to what I needed.



Maybe there's a better way to go about this task? Thanks in advance :)



- (void) switchMovie;
{

NSURL *movieImageUrl = [movieImageUrlArray objectAtIndex:index];
NSData *data = [NSData dataWithContentsOfURL:movieImageUrl];
UIImage *movieImage = [[UIImage alloc] initWithData:data];
UIImageView *image = [[UIImageView alloc] initWithImage:movieImage];

image.alpha = 0.0f;
[self addSubview:image];

if (moviePlayer1Playing) {

moviePlayer1Playing = NO;
moviePlayer2Playing = NO;

[moviePlayer1 pause]; //pausing later in the method caused a crash, stopping causes a crash.

[UIView animateWithDuration:1.0
delay:0.0
options:UIViewAnimationCurveEaseIn
animations:^{

image.alpha = 1.0f; //fade in still of first frame of new movie

} completion:^(BOOL finished) {

[moviePlayer1 release]; //release original movie.

moviePlayer2 = [[MPMoviePlayerController alloc] initWithContentURL:[movieUrlArray objectAtIndex:index]];

moviePlayer2.shouldAutoplay = NO;
[moviePlayer2 prepareToPlay];
[moviePlayer2 setControlStyle:MPMovieControlStyleNone];
moviePlayer2.scalingMode = MPMovieScalingModeAspectFill;
[moviePlayer2.view setFrame:CGRectMake(0, 0, 1024 , 768)];
moviePlayer2.view.backgroundColor = [UIColor clearColor];
moviePlayer2.view.alpha = 0.0;
[self addSubview:moviePlayer2.view];

[UIView animateWithDuration: 3.0
delay: 0.0
options: UIViewAnimationCurveLinear
animations:^(void){

moviePlayer2.view.alpha = 1.0f;
//During this transition the view goes dark half-way through, before lightening again.

} completion:^ (BOOL finished) {

[moviePlayer2 play];
moviePlayer2Playing = YES;
moviePlayer1Playing = NO;


}];

}];


}




Detecting button clicks within a for loop in an Android app

I'm having a little bit of trouble. There are 12 buttons, and 10 questions in my android app. If I ran a for loop for all of the questions is there a way that I can check if a button is pushed and if it's the answer to the current question? Then it would move on to the next question, and do the same until the loop ended. I don't know exactly how to word it, but I hope you can figure out what I mean.





Disabling button from another class

I know this question has been asked before or similar questions asked but none of the solutions has yet fixed my problem.



I have a winform that has a button named hitButton. All I need to do is to disable this button from another class (i.e. not the form class).



My form class is:



public partial class BlackJackTable : Form
{
}


My separate class is:



class GameWon
{
}


I have tried exposing a public method in BlackJackTable like this:



public void DisableButtons()
{
hitButton.Enabled = false;
}


and accessing from GameWon constructor (it doesn't seem to matter where in the class I access it from though) like this:



public BlackJackTable blackJackTable = new BlackJackTable();

public GameWon()
{
blackJackTable.DisableButtons();
}


I have tried using a variable in GameWon:



public Button hit;


and assigning from blackJackTable:



GameWon gameWon = new GameWon();

public void Assign()
{
gameWon.hit = this.hitButton; // or just = hitButton;
}


and disabling from GameWon:



hit.Enabled = false;


I have tried a couple of other things but none of them work. I'm guessing I'm missing something obvious as none of the methods I've tried have worked.



Any thoughts appreciated!



Update



I have managed to do the latter method with textboxes and pictureboxes, what's the difference with a button?





Populate a ListView with an AsyncTask failing to populate

Trying to get this working... it loads up fine, even tells the application that it completed getting all the data. It does not populate the listview though.



The data response inside show_list: [A, B, C, D]



public class MainActivity extends ActionBarActivity {
private static final String DEBUG_TAG = "MainActivity";
private boolean mAlternateTitle = false;
List<Show> mShowList;
AlertDialog mAlertDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadTitles();
}

private void loadTitles() {
ShowsList show_list = new ShowsList();
show_list.execute();
}

private class ShowsList extends AsyncTask<Void, Void, List<Show>> {
@Override
protected void onPreExecute() {
mAlertDialog = new AlertDialog.Builder(MainActivity.this).setIcon(R.drawable.ic_action_refresh).setTitle(R.string.fetching_new).show();
}

@Override
protected List<Show> doInBackground(Void... voids) {
try {
mShowList = Show.getShows();
return mShowList;
} catch (Exception e) {
new AlertDialog.Builder(MainActivity.this.getApplicationContext()).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.server_down_title).setMessage(R.string.server_down_message).setPositiveButton(R.string.app_quit, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.this.finish();
}
}).show();
return null;
}
}

@Override
protected void onPostExecute(final List<Show> show_list) {
final String DEBUG_TAG = "MainActivity$ShowList$onPostExecute";
/*ListView lv = (ListView) findViewById(R.id.list);
ArrayAdapter<Show> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, async_show_list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new ListClickListener());
*/
if (mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}

try {
ListView lv = (ListView) findViewById(R.id.list);
ShowsAdapter adapter = new ShowsAdapter(MainActivity.this, android.R.layout.simple_list_item_1, show_list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new ListClickListener());
Log.d(DEBUG_TAG, adapter.toString());
adapter.notifyDataSetChanged();
//adapter.add(show_list[0]);
} catch (Exception e) {
new AlertDialog.Builder(MainActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.server_down_title).setMessage(R.string.server_down_message).setPositiveButton(R.string.app_quit, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.this.finish();
}
}).show();
}
}
}

private class ListClickListener implements AdapterView.OnItemClickListener {
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Show show = mShowList.get(i);
Toast.makeText(MainActivity.this, "Clicked on a list item: " + show.title, Toast.LENGTH_LONG).show();
}
}

private class ShowsAdapter extends ArrayAdapter<Show> {
public ShowsAdapter(Context context, int textViewResourceId, List<Show> shows) {
super(context, textViewResourceId, shows);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
Show show = this.getItem(position);

if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_row_show, parent, false);
}

((TextView) convertView.findViewById(R.id.show_title)).setText(show.title);
//((TextView) convertView.findViewById(R.id.episode_number)).setText(episode.getGrayLine());

return convertView;
}
}




Random image in a .php file

Im trying to make a random image display with php. Now im not talking about something that echos "image", I need something that when I view the .png file I will see a random image everytime. I wasnt sure what to search for so Im gonna ask it here. I saw someone do it before, where they 'tricked' the browser into thinking it was a .png file, when it was just some php using something to pick a random image and set it as the file.





BackboneJS root level views

If you have some root level HTML that is present on "almost" every screen, where/how would you organize this?



I'm using backbone-boilerplate and requirejs. One of the root level views is a global navigation element that can be invoked from the bottom of the screen at any time.



This is organized in a module that has a model (for visibility, the selected state, the log of clicks, etc). The app is stored in:



ClientName.app = _.extend( { rootViews: {} }, Backbone.Views);


Then in my routers initialize method, i have:



ClientName.app.rootViews.globalNav = new GlobalNav.Views.BottomView({ model: new GlobalNav.Models.Bottom()});


It works fine, but as the functionality is growing, the routers initialize method is getting out of hand with similar root views, sub routers, etc. Am I totally missing something?



What would you recommend?





Why doesn't this rememberUser() function work?

I have written a function to remember the user that has just logged in. It looks to me that it should work, but no Idea why it doesn't work. The problem is that the cookie doesn't get made when I look into my browser's stored cookies.



This is the function I'm talking about:



function rememberUser($id) {

$mysqli = new mysqli('bla', 'blabla', 'blablablaa', 'blaaaaa');
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$remember = md5(uniqid(mt_rand(),true));
$stmt = $mysqli->prepare("UPDATE USERS SET USER_REMEMBER_KEY = ? WHERE USER_ID = ?");
$stmt->bind_param('si', $remember, $id);
$stmt->execute();
setcookie("remember", $remember, time()+60*60*24*30, "/", "www.someSite.com", false, true);
}


I should mention that the query works fine and USER_REMEMBER_KEY is stored fine in the DB. So the problem is really the cookie, I think.



Does anyone see the problem here? Thanks in advance.



UPDATE: I'm using Google Chrome BETA version 19.xx





alternative to Uniformjs for styling select and check boxes?

Uniformjs seems to be unmaintained now (last commit 2 years ago). Is there another solid javascript library that allows you to style select, radio and check boxes?





Object Assignment vs Object Creation

I have always found it hard to decide when I should create a single object and pass it to every object that needs it, or create a new object for every object which needs that item.



Some cases are so obvious, like entity objects which are readonly after allocation and instantiation. You can pass the same object anywhere and not worry about another object modifying it, which ruins the other objects holding a reference to it.



My problem mainly lies with objects that represent themselves to the user. Objects like CCSprite in cocos2d, NSMenuItem in Cocoa (AppKit) and other objects with visual representation..









Examples:



In cocoa, i know that I have to create an NSMenu for each NSPopUpButton, so that the selection for a specific button does not affect the rest. But, what about the NSMenuItems contained within? Can I create a single set and pass them to all the menus? What are your grounds, or how did you come to such a conclusion?



Other example:



In cocos2d, and almost all GUI based applications, you can pass to a button two images/sprites/...etc. such that one is for the normal state, and the other is for the selected (highlighted, pressed, clicked) state. Can I pass the same image/sprite/...etc. to both, making them point to the same object?



I hope this is not an implementation related issue (that it ultimately depends on the implementation) , since I face it in a lot of my programming projects, in cocoa, cocos2d, Java ... etc.



PS: I need help with choosing the proper tags





Ohm, find all records from array of ids

I am looking for a way to find all Ohm affiliated objects with one query, by feeding it an array of attributes that are indexed. In Mongoid, this is done with something like:



Foo.any_in(:some_id => [list_of_ids])


ActiveRecord has the find_all family of methods.



I essentially want to be able to pull N records from the data store without calling find() 30 times individually.





How to display only one data at a time in an online quiz

I've previously made a text file and turned it into multidimensional array to display as the questions for my quiz.



Note: I am unable to insert images therefore I cannot provide any example so I'll try to be as descriptive as I can.



I'm trying to display only one question at a time, every time a user clicks on my quiz.



This is my code so far. The main.php page:



<h2>ONLINE QUIZ</h2>
<ul>
<li><a href='question.php'>Take quiz</a></li>
<li><a href='module.php'>Admin Module</a></li>
</ul>
<?php

$file = fopen('data.txt', 'r');

$array = array();
while ($line = fgetcsv($file)) {
$array[] = $line;
}

fclose($file);

session_start();
$_SESSION["questions_array"]=$array;

?>


And the question.php page:



<?php

session_start();
$array=$_SESSION["questions_array"];

foreach ($array as $q => $data) {
echo '<p>'.array_shift($data).'</p>';
foreach ($data as $a => $answer) {
echo
' <input type="radio" name="question-'.$q.'" id="question-'.$q.'"'.
' value="'.$a.'"/>'.
' <label for="question-'.$q.'">'.$answer.'</label>'.
'<br>';
}

}

?>


When the Take quiz link is clicked, the user is taken to the question page where only one question is shown. The user then picks an answer and hits submit. This submit button will take the user to the result page where they can then hit continue.



The Continue link will redirect them back to the question page where the next question is displayed.



From stuff that I've done before, I am attempting to use the isset() function to make this happen. However, the problem is that I'm not sure how exactly to write my isset().



I've found this snippet from this site, I'm not sure if it's useful, but:



if (!isset($_SESSION['FirstVisit'])) {

//show site for the first time part
$_SESSION['FirstVisit] = 1;
header("Location: http://example.com/index.php");

// Don't forget to add http colon slash slash www dot before!

} else { Show normal site }


But once again I found myself blank. How exactly do I use the isset() to display only one question?





Can I get the table, column and type information from a model?

I'm using ruby and activerecord to get information about a mysql table.



I was hoping I could get this information directly from my model class, is this possible?



Say I have my model:



class Product < ActiveRecord::Base
end


Is it now possible for me to get information regarding:



1. mysql table
2. columns
3. column types


Or do I have to look somewhere deeper into the ActiveRecord module to get this?





CUDA: bad performance with shared memory and no parallelism

I'm trying to exploit shared memory in this kernel function, but the performance are not as good as I was expecting. This function is called many times in my application (about 1000 times or more), so I was thinking to exploit shared memory to avoid the memory latency. But something is wrong apparently because my application became really slow since i'm using shared memory.

This is the kernel:



__global__ void AndBitwiseOperation(int* _memory_device, int b1_size, int* b1_memory, int* b2_memory){
int j = 0;

// index GPU - Transaction-wise
unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;
unsigned int tid = threadIdx.x;

// shared variable
extern __shared__ int shared_memory_data[];
extern __shared__ int shared_b1_data[];
extern __shared__ int shared_b2_data[];

// copy from global memory into shared memory and sync threads
shared_b1_data[tid] = b1_memory[tid];
shared_b2_data[tid] = b2_memory[tid];
__syncthreads();

// AND each int bitwise
for(j = 0; j < b1_size; j++)
shared_memory_data[tid] = (shared_b1_data[tid] & shared_b2_data[tid]);

// write result for this block to global memory
_memory_device[i] = shared_memory_data[i];
}


The shared variables are declared extern because I don't know the size of b1 and b2 since they depend from the number of customer that I can only know at runtime (but both have the same size all the times).

This is how I call the kernel:



void Bitmap::And(const Bitmap &b1, const Bitmap &b2)
{

int* _memory_device;
int* b1_memory;
int* b2_memory;

int b1_size = b1.getIntSize();

// allocate memory on GPU
(cudaMalloc((void **)&b1_memory, _memSizeInt * SIZE_UINT));
(cudaMalloc((void **)&b2_memory, _memSizeInt * SIZE_UINT));
(cudaMalloc((void **)&_memory_device, _memSizeInt * SIZE_UINT));

// copy values on GPU
(cudaMemcpy(b1_memory, b1._memory, _memSizeInt * SIZE_UINT, cudaMemcpyHostToDevice ));
(cudaMemcpy(b2_memory, b2._memory, _memSizeInt * SIZE_UINT, cudaMemcpyHostToDevice ));
(cudaMemcpy(_memory_device, _memory, _memSizeInt * SIZE_UINT, cudaMemcpyHostToDevice ));

dim3 dimBlock(1, 1);
dim3 dimGrid(1, 1);

AndBitwiseOperation<<<dimGrid, dimBlock>>>(_memory_device, b1_size, b1_memory, b2_memory);

// return values
(cudaMemcpy(_memory, _memory_device, _memSizeInt * SIZE_UINT, cudaMemcpyDeviceToHost ));

// Free Memory
(cudaFree(b1_memory));
(cudaFree(b2_memory));
(cudaFree(_memory_device));
}


b1 and b2 are bitmaps with 4 bits for each element. The number of elements depend from the number of customers. Also, I have problem with the kernel's parameters, because if I add some blocks or threads, the AndBitwiseOperation() is not giving me the correct result. With just 1 block and 1 thread per block the result is correct but the kernel is not in parallel.

Every advice is welcomed :)

Thank you





Posting data to a HTTPS page

If I have a page outside of my site, and it posts to an HTTPS page on my site (SSL is setup), will the server and client exchange keys before the data is posted and then encrypt the data, or will the data be posted in plain text from the client to the server, then be given the key to encrypt?



Thank you,





Trying to bind the height/width of a grid to a ViewModel

So I have a grid inside a viewbox. Now the grid scales with the viewbox fine. However, I need to know the height and width of the grid in my ViewModel. However it doesn't seem to ever set the Height to anything?



<Viewbox VerticalAlignment="Top" Margin="5,20,5,0">
<Border BorderThickness="6" BorderBrush="Black" CornerRadius="2">

<Grid MinHeight="300" MinWidth="400" Height="{Binding Height, Mode=TwoWay}" Width="{Binding Width, Mode=TwoWay}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="0" >
<ItemsControl ItemsSource="{Binding Viewers}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding X}" />
<Setter Property="Canvas.Top" Value="{Binding Y}"/>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
</Grid>
</Border>
</Viewbox>


And in my ViewModel:



    private int _height;
public int Height
{
get
{
return _height;
}

set
{
_height = value;
OnPropertyChanged("Height");
}
}

private int _width;
public int Width
{
get
{
return _width;
}

set
{
_width = value;
OnPropertyChanged("Width");
}
}


Any ideas?





Triangle partitioning

This was a problem in the 2010 Pacific ACM-ICPC contest. The gist of it is trying to find a way to partition a set of points inside a triangle into three subtriangles such that each partition contains exactly a third of the points.



Input:




  • Coordinates of a bounding triangle: (v1x,v1y),(v2x,v2y),(v3x,v3y)

  • A number 3n < 30000 representing the number of points lying inside the triangle

  • Coordinates of the 3n points: (x_i,y_i) for i=1...3n



Output:




  • A point (sx,sy) that splits the triangle into 3 subtriangles such that each subtriangle contains exactly n points.



The way the splitting point splits the bounding triangle into subtriangles is as follows: Draw a line from the splitting point to each of the three vertices. This will divide the triangle into 3 subtriangles.



We are guaranteed that such a point exists. Any such point will suffice (the answer is not necessarily unique).



Here is an example of the problem for n=2 (6 points). We are given the coordinates of each of the colored points and the coordinates of each vertex of the large triangle. The splitting point is circled in gray.



enter image description here



Can someone suggest an algorithm faster than O(n^2)?





jquery output id display as [object object]

var str = prompt("What is your name?");
var str1=$(str).html('<b>'+str+'</b>');
alert(str1);


By above code I'm getting [object object] as output ,. please help