Monday, May 14, 2012

Mongo DB Delete a field and value

In mongo shell how would I delete all occurrences of "id" : "1" the value of the field is always different. Would I use the $unset operator? Would that delete the value and the field?





Javascript Phone number validation Paratheses sign

I did some searching and there where others asking this question and answers to it but none that seemed to fit what I was trying to do. Basically I'm working on a validation of the phone entry that accepts (123)4567890 as an entry. I've already implemented one that accepts a simple number string such as 1234567890 and one with dashes 123-456-7890. I know I'm making a simple mistake somewehre but I can't figure out what I'm doing wrong.



Here's the phone number with dashes form that is working:



//Validates phone number with dashes. 
function isTwelveAndDashes(phone) {

if (phone.length != 12) return false;

var pass = true;

for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);

if (i == 3 || i == 7) {
if (c != '-') {
pass = false;
}
}
else {
if (!isDigit(c)) {
pass = false;
}
}
}

return pass;
}?


and this is the one I can't manage to work out.



function isTwelveAndPara(phone) {
if (phone.length != 12) return false;

var pass = true;

for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);

if (i == 0) {
if (c != '(') {
pass = false;
}
}

if (i == 4) {
if (c != ')') {
pass = false;
}
}
else {
if (!isDigit(c)) {
pass = false;
}
}
}

return pass;
}?




using perl hashes to handle tab-delimited files

I have two files: file 1 has 3 columns(SNP, Chromosome,position) and file 2 has 3 columns(Chromosome, peak_start and peak_end). All columns are numeric except for the SNP column.



If chromosome in file 1 matches file 2, i want to check if the position of the SNP lies in between peak_start and peak_end. If yes, show which SNP falls in which peak (preferably write output to a tab-delimited file). I would prefer to split the file, and use hashes where the chromosome is the key. I have found only a few questions remotely similar to this but i could not understand well the suggested solutions.
Here is the example of my code. It is only meant to illustrate my question and so far doesn't do anything so think of it as "pseudocode". Also, please forgive the formatting, this is my first time to ask a question here and i am a biologist trying to learn perl programming!



#!usr/bin/perl

use strict;
use warnings;

my (%peaks, %X81_05);
my @array;

#open file or die

unless (open (FIRST_SAMPLE, "X81_05.txt")) {
die "could not open X81_05.txt";
}

#split the tab-delimited file into respective fields

while (<FIRST_SAMPLE>) {

chomp $_;
next if (m/Chromosome/); #skip the header

@array = split("\t", $_);
($chr1,$pos,$sample) = @array;


$X81_05{'$array[0]'} = (

'position' =>'$array[1]'
)

}

close (FIRST_SAMPLE);

#open file using file handle
unless (open (PEAKS, "peaks.txt")) {
die "could not open peaks.txt";
}

my ($chr, $peak_start, $peak_end);


while (<PEAKS>) {
chomp $_;

next if (m/Chromosome/); #skip header
($chr, $peak_start, $peak_end) = split(/\t/);
$peaks{$chr}{'peak_start'} = $peak_start;
$peaks{$chr}{'peak_end'} = $peak_end;

}


close (PEAKS);

for my $chr1 (keys %X81_05) {
my $val = $X81_05{$chr1}{'position'};

for my $chr (keys %peaks) {
my $min = $peaks{$chr}{'peak_start'};

my $max = $peaks{$chr}{'peak_end'};

if ( ($val > $min) and ($val < $max) ) {
#print $val, " ", "lies between"," ", $min, " ", "and", " ", $max, "\n";

}else {
#print $val, " ", "does not lie between"," ", $min, " ", "and", " ", $max, "\n";
}
}
}


more awesome code





Rails server says port already used, how to kill that process?

I'm on a mac, doing:



rails server



I get:



2010-12-17 12:35:15] INFO  WEBrick 1.3.1
[2010-12-17 12:35:15] INFO ruby 1.8.7 (2010-08-16) [i686-darwin10.4.0]
[2010-12-17 12:35:15] WARN TCPServer Error: Address already in use - bind(2)
Exiting


I know I can start one on a new port, but I want to kill this process.





Nested list back button sencha touch 2

I need to get value of back button of in nested list sencha touch 2 .. but it returns only back because it set default to back .. is there any way to get the actual value of it ?





make sure img div loads before video div

I have a page where when you click one out of a set of buttons, and image pops up and then fades as a video plays. The problem is that it works on the first click, but on the second on, the div with the image loads after the video loads. How can I make sure it appears before the video starts to load? the script (simplified) is



$('li, .thumbs').on('click', function() {
myVideo.load();
myVideo.play();
$('#myVid').bind("loadstart", function() {
$('#MyT').fadeIn(0);
});
$('#myVid').bind("playing", function() {
$('#MyT').fadeOut(500);
});
});?




select from one table where count=1 in second table and two more conditions

I need to select transactions with cash payment and same date but only for those transactions
which have only one payment ( so num 14 should be omitted from resultset )
So correct result is 12 and 13 only.



    Table2                          Table1
num | date | data | total num | payment | date
12 xy abc 2.5 12 cash xy
13 xy cbc 2.1 13 cash xy
14 xy acc 2.3 14 visa xy
19 xy def 2.0 14 cash xy
27 xy fgh 1.3 19 visa xy
27 mc xy


Something like this gives num 14 in result-set but 14 should be omitted.



SELECT num, data 
FROM Table2
WHERE num IN
(
SELECT num FROM `Table1`
WHERE payment = 'cash'
GROUP BY `num`
HAVING ( COUNT(`num`) = 1 )
)


To sumarize correct answer (by tombom ):



 SELECT t2.num, t2.data 
FROM Table1 as t1
INNER JOIN Table2 as t2 ON t1.num = t2.num
AND t1.date = 'xy'
GROUP BY t1.num
HAVING GROUP_CONCAT(t1.payment) = 'cash'


Thanks!





Unable to select menu item using xpath [Validates in Xpath checker, but webdriver cannot find it]

I am trying to select a menu item...though xpath validates well in Xpath checker, it does not work from WebDriver ...can someone help?



I get Unable to locate element: {"method":"xpath","selector":"//a[contains(text(),'Start Loan Process')]"}



HMTL looks something like this
<div class="bd">
<ul class="first-of-type">
<li id="yui-gen7" class="yuimenuitem first-of-type" groupindex="0" index="0">
<li id="yui-gen8" class="yuimenuitem" groupindex="0" index="1">
<li id="yui-gen9" class="yuimenuitem" groupindex="0" index="2">
<li id="yui-gen10" class="yuimenuitem" groupindex="0" index="3">
<li id="yui-gen11" class="yuimenuitem" groupindex="0" index="4">
<a class="yuimenuitemlabel" href="#">Start Loan Process</a>




Precision/recall for multiclass-multilabel classification

I'm wondering how to calculate precision and recall measures for multiclass multilabel classification, i.e. classification where there are more than two labels, and where each instance can have multiple labels?



Thanks,



MaVe





Javascript: Calculate width of div as sum of images

Basically, I need "style="width:__" to be added to the "img-container' div, with the width being the sum of all the images and their padding. The images and image widths are added in dynamically through a CMS, which is why I need the javascript to calculate the width dynamically.



<div id='img-container'[HERE IS WHERE I NEED THE WIDTH TO BE ADDED]>
<div class='picture_holder' >
<div class='picture' >
<img src="{image}" style='width:{width}px;padding-right:10px;'/>
<div class='captioning'>{caption}</div>
</div>
</div>
</div>


I don't know javascript at all, but tried to piece something together (I didn't even get to adding in the padding yet):



<script type="text/javascript">
var $name = ('div#img-container');
var Imgs = div.getElementsByTagName('img');
var w = 0;
for ( var i = 0; i < Imgs.length; i++ ){
w += parseInt(Imgs[i].offsetWidth);
}
</script>


It's obviously not working at all though. Any help would be much appreciated!





How to add a List of JButtons to a JFrame?

So... I'm making a Jeopardy game, and I'm experimenting with better ways of making and adding the buttons so that it looks better in the source code. So to start off, I have a CategoryClass that takes the parameters of a List of QuestionButtons (basically a JButton), the category name and so on. The only trouble I'm having is adding the buttons to a JPanel. Here's the code:



    public void addCategoryButtons(JPanel pane) {
JLabel head = this.getCategoryHeading();
pane.add(head);
List<QuestionButton> buttons = this.getCategoryButtons();
for (int i = 0; i < buttons.size(); i++) {
pane.add(buttons.get(i).getButton());
}
}


And here's what I get. Note: the "Test" is the name of the category



As you can see, It shows the last Category I add instead of all of them. Any suggestions?





Android Emulator Won't Start App on Eclipse

When I try to start an app to test it in the emulator, the emulator opens, then it installs the app (according to LogCat,) but it doesn't run. I looked in the applications, but it's not there. I have tried recreating the emulator, starting it from AVD Manager, resetting ADB, and more. This what LogCat gives me when I start the emulator:



[2012-05-13 20:25:23 - StickFigure] Launching a new emulator with Virtual Device 'Droid'
[2012-05-13 20:25:27 - Emulator] emulator: emulator window was out of view and was recentered
[2012-05-13 20:25:28 - Emulator]
[2012-05-13 20:25:28 - StickFigure] New emulator found: emulator-5554
[2012-05-13 20:25:28 - StickFigure] Waiting for HOME ('android.process.acore') to be launched...
[2012-05-13 20:26:04 - StickFigure] HOME is up on device 'emulator-5554'
[2012-05-13 20:26:04 - StickFigure] Uploading StickFigure.apk onto device 'emulator-5554'
[2012-05-13 20:26:04 - StickFigure] Installing StickFigure.apk...
[2012-05-13 20:26:28 - StickFigure] Success!
[2012-05-13 20:26:28 - StickFigure] /StickFigure/bin/StickFigure.apk installed on device
[2012-05-13 20:26:28 - StickFigure] Done!




How to create a list of totals for durations?

I want to calculate a bonus based on the two consecutive months where sales where the most. So I can iterate a total for every two consecutive months to find the Max value ie get



value = Max[total_between_firstdayMonth1_and_lastDayMonth2, total_between_firstdayMonth2_and_lastDayMonth3, ... , total_between_firstdaySecondToLastMonth_andlastDayLastMonth]



So I might need a list of pairs of datetime objects or something similar.



start= model.Order.order('created').get().created # get the oldest order
end = model.Order.order('-created').get().created # get the newest order


So inbetween start and end I must partition the time in overlapping pairs of consecutive 2 months eg. if first order was in december 2008 and the last order was in november 2011 then the list from where to pick the max should be [total_december2008 + total_january2009, total_january2009 + total_february2009, ... , total_october2011 + total_november2011]



But then how do I get the last day of the second month if I know the start like above? How can I create the list of times and totals?



I might not be able to create the list of totals right away but if I can create the list of starts and ends then I can call a helper function we can assume eg.



total(start_datetime, end_datetime)



Thanks for any help



Update



I think I found how to calculate the time for an example interval where the timeline is from any date to last day next month:



>>> d = date(2007,12,18)
>>> print d
2007-12-18
>>> d + relativedelta(months=2) - timedelta(days=d.day)
datetime.date(2008, 1, 31)


Update 2



I can calculate upto the first level the first duration. Now I only have to generalize it to loop through all the durations and check which was the highest level:



def level(self):
startdate = model.Order.all().filter('status =', 'PAID').filter('distributor_id =' , self._key.id()).get().created.date()
last_day_nextmonth =startdate + relativedelta(months=2) - timedelta(days=1)
if self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth) < 25:
maxlevel = _('New distributor')
elif self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth) > 25:
maxlevel = _('Assistant Teamleader')
return maxlevel


Update 3



Closer to what I mean is taking the max of some function values from beginning up to now. Basecase can be that last day next month is is the future and the helper function can be recursive but I didn't have time or help to make it recursive to it only works for the first 2 periods now ie 4 months from start:



def level(self):
startdate = model.Order.all().filter('status =', 'PAID'
).filter('distributor_id =',
self._key.id()).get().created.date()
last_day_nextmonth = startdate + relativedelta(months=2) \
- timedelta(days=1)
total = self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)
if total >= 125:
level = 5
elif total >= 75:
level = 4
elif total >= 25:
level = 3
elif total >= 2:
level = 2
else:
level = 1
return self.levelHelp(level, last_day_nextmonth + timedelta(days=1))

def levelHelp(self, level, startdate):
#if startdate in future return level
last_day_nextmonth = startdate + relativedelta(months=2) \
- timedelta(days=1)
total = self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)
if total >= 125:
newlevel = 5
elif total >= 75:
newlevel = 4
elif total >= 25:
newlevel = 3
elif total >= 2:
newlevel = 2
else:
newlevel = 1
return level if level > newlevel else newlevel


Update 4



I added the recursion where base case is that next step is in the future, if so it will return the max level:



def level(self):
startdate = model.Order.all().filter('status =', 'PAID'
).filter('distributor_id =',
self._key.id()).get().created.date()
last_day_nextmonth = startdate + relativedelta(months=2) \
- timedelta(days=1)
total = self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)
if total >= 125:
level = 5
elif total >= 75:
level = 4
elif total >= 25:
level = 3
elif total >= 2:
level = 2
else:
level = 1
return self.levelHelp(level, last_day_nextmonth + timedelta(days=1))

def levelHelp(self, level, startdate):

last_day_nextmonth = startdate + relativedelta(months=2) \
- timedelta(days=1)
total = self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)
if total >= 125:
newlevel = 5
elif total >= 75:
newlevel = 4
elif total >= 25:
newlevel = 3
elif total >= 2:
newlevel = 2
else:
newlevel = 1

maxlevel = level if level > newlevel else newlevel

nextstart = last_day_nextmonth + timedelta(days=1)
now = datetime.now().date()
if nextstart > now: #next start in is the future
return maxlevel
else: return self.levelHelp(maxlevel, nextstart)




How to apply attirbutes like [Display( = "displayname"]) on a model with model-first design?

I am using MVC and entity framework. I started with code first design and I was applying attributes like [Required] and [Display] but how do I do this if I am using a model first? I created my database model already.



Thank you.





Select from table, name is stored in the field

How can I join some data from some table whose name is a field of the dataset?



Like this:



SELECT *
FROM dataset
INNER JOIN dataset.table_name
ON dataset.param_id = (dataset.table_name).id_(dataset.table_name)




Search for strings in file and add certain line values to ArrayList

I am trying to write a method that reads a list from file1, search for list values in file2 and add parts of the line containing list values to arraylist until the string "Total" is reached.



here is sample file1:



AAA00015
AAA00016
AAA00017
AAA00018
AAA00019
AAA00020
AAA00021
AAA00022
AAA00023
AAA00024
AAA00025
AAA00026


file2:



ABC BANK
ATM TRANSACTION SUMMARY

Institution: ABC BANK
Time 13:30:46
Date: 13/05/2012


1000 ATM AAA00022 01 10000.00/ 0.00/ 10000.00 100 289.00 1 0.00 0 0.00 0
2000 ATM AAB00023 02 20000.00/ 0.00/ 20000.00 200 0.00 0 0.00 0 0.00 0
3000 ATM AAC00024 03 30000.00/ 0.00/ 30000.00 300 0.00 0 0.00 0 0.00 0
_________________________________________________________________________________________________________________________________________
Total 60000.00/ 0.00/ 60000.00 600 289.00 1 0.00 0 0.00 0

1000 ATM AAA00022 01 10000.00/ 0.00/ 10000.00 100 289.00 1 0.00 0 0.00 0
2000 ATM AAB00023 02 20000.00/ 0.00/ 20000.00 200 0.00 0 0.00 0 0.00 0
3000 ATM AAC00024 03 30000.00/ 0.00/ 30000.00 300 0.00 0 0.00 0 0.00 0


Here is my code:



import java.io.*;
import java.util.*;

public class atmTotals
{
ArrayList <String> atmList = new ArrayList <String>();
ArrayList <Atm> atmUs = new ArrayList <Atm>();

public void getAtmList()
{
try
{
FileReader in = new FileReader("ATMList.txt");
Scanner listIn = new Scanner(in);
while (listIn.hasNextLine())
{
atmList.add(new String (listIn.next()));
}
for (String list : atmList)
{
//System.out.println(list);
}
}

catch( FileNotFoundException fileNotFound)
{
System.err.println( "Error opening file.");
System.exit(1);
}
catch ( NoSuchElementException elementEx)
{
System.err.println( "Incorrect file format.");
System.exit(1);
}
catch ( IllegalStateException stateEx )
{
System.err.println( "Error reading from file.");
System.exit(1);
}

}
public void getAtmTotals()
{
try
{
FileReader file = new FileReader ("ATMTOTAL.rep");
Scanner in = new Scanner (file).useDelimiter("\\s\\s+");
for (String list : atmList)
{
while (in.hasNext() && !(in.next().contains("Total")))
{
String currentLine = in.next();
if (currentLine.contains(list))
{
System.out.println("Found String " + currentLine);
atmUs.add ( new Atm (in.next(), in.next(), in.nextFloat()));
}
}
}
//System.out.print(atmUs);

for ( Atm list : atmUs)
{
System.out.printf("%-15s%-3s%10.2f\n", list.getAtmID(), list.getBranchID(), list.getTotalAmt());
}

}
catch( FileNotFoundException fileNotFound)
{
System.err.println( "Error opening file.");
System.exit(1);
}
catch ( NoSuchElementException elementEx)
{
System.err.println( "Incorrect file format.");
System.exit(1);
}
catch ( IllegalStateException stateEx )
{
System.err.println( "Error reading from file.");
System.exit(1);
}
}
}


Constructor:



public class Atm 
{
private String AtmID;
private String branchID;
private float TotalAmt;


public Atm ( String AtmID, String branchID, float TotalAmt )
{
this.AtmID = AtmID;
this.branchID = branchID;
this.TotalAmt = TotalAmt;
.....


I get output:



Found String AAA00022
Incorrect file format.




Wordpress next/prev post link with image

I'm trying to use an image for the previous and next post links. The following line of code was rejected as I should use the get_template_directory_uri(). How should I amend the following code in php to include this function?



<?php next_posts_link('<img src="./wp-content/themes/Icecap/images/next.png" />'); ?>




Hide the cursor of an UITextField [Edited with a solution]

Now we have a UIButton styled as a combo button and custom methods to show a UIPickerView like the keyboard does. In our views with editable controls we detect if we are editing an UITextField or a combo button and then shows the usual keyboard or the picker in our custom way.



But since iOS 3.2 UITextField has the inputView property and it can show an input view different than the usual UIKeyboard.



I'm implementing this approach to simplify things (animation of the picker, centralization of the events in the UITextFieldDelegate methods, etc).



I'm very close to the final implementation but I have a problem: can I hide the cursor? I don't want to not allow editing and track touches because then I will have the same behaviour than with the UIButton. I want to delegate all the event handling to the UITextFieldDelegate and don't implement actions on touch events.



Thank you!



EDIT: I think I have the correct solution but If it can be improved will be welcome :) Well, I made a subclass of UITextField and overriden the method that returns the CGRect for the bounds



-(CGRect)textRectForBounds:(CGRect)bounds {
return CGRectZero;
}


The problem? The text doesn't show because the rect is zero. But I added an UILabel as a subview of the control and overridden the setText method so, as we enter a text as usual, the text field text is nil and is the label which shows the text



- (void)setText:(NSString *)aText {
[super setText:nil];

if (aText == nil) {
textLabel_.text = nil;
}

if (![aText isEqualToString:@""]) {
textLabel_.text = aText;
}
}


With this the thing works as expected. Have you know any way to improve it?



EDIT 2 I found another solution: subclass UIButton and override these methods



- (UIView *)inputView {
return inputView_;
}

- (void)setInputView:(UIView *)anInputView {
if (inputView_ != anInputView) {
[inputView_ release];
inputView_ = [anInputView retain];
}
}

- (BOOL)canBecomeFirstResponder {
return YES;
}


Now the button, as a UIResponder, have a similar behavior than UITexxField and an implementation pretty straightforward.





ruby multiple connections and dns queries

http = Net::HTTP.new("hostname", 80)
http.open_timeout = 300
http.read_timeout = 300

pagereq = lambda {
http.request(Net::HTTP::Get.new(page, {"User-Agent" => "Mozilla/5.0"})).body }

some_conditions.to_a.each do |n|

page = "startpage"+n.to_s

pagereq.call.scan(/criteria1/).each do |m|
page = "/"+m.to_s
puts pagereq.call.scan(/criteria2/)
end

end


I use this template to collect links or something else from sites. It produce DNS resolving on each connection and this is not good.



What I interest in. Resolve hostname one time, make connection, make all operations, close connection.





Modulus division returns an integer?

Does modulus division only return integers? I need a float return. See the following:



var_dump(12 % 10); // returns 2, as expected
var_dump(11.5 % 10); // returns 1 instead of 1.5?




PHP foreach / while / loop - how to traverse entire category hierarchy without database

I need to fetch the whole category tree hierarchy(ebay API) and print each category value without to use any database (i.e. mysql ). I've tried several approaches using foreach and while but my script dies after the top categories or at most after the first set of child categories . Here is my script :



error_reporting(E_ALL);
## get categories allow us to traverse through categories

//getcategorycall call to return the categories based on the category id
function GetCategoryInfo($id)
{
$URL = "http://open.api.ebay.com/Shopping?callname=GetCategoryInfo&appid=mihaibcdd-e1d6-40e3-933c-0feab57069f&siteid=0&CategoryID=$id&version=767&responseencoding=JSON&includeSelector=ChildCategories";
$response = json_decode(file_get_contents($URL), true);
//check if the request is returned with success
$Ack = $response['Ack'];
if($Ack!=='Success')
{
echo "error $Ack";
exit();
}
//get category array
$CategoryArray = $response['CategoryArray']['Category'];
return $CategoryArray;
}

$CategoryID_top = '-1';

$CategoryInfo = GetCategoryInfo($CategoryID);
//traverse top categories
//we need to count the categories and start from 1 due the fact the requested category(e.g. root) is included in the response
$top_count = count($CategoryInfo);
$top_i = 1;
while($top_i <= $top_count)
{
$Category = $CategoryInfo[$top_i];
# print_r($Category);
# exit();
$CategoryID = $Category['CategoryID'];
$CategoryName = $Category['CategoryName'];
$LeafCategory = $Category['LeafCategory'];
echo " Top category:: $CategoryID\n $CategoryName\n $LeafCategory\n <br>";


//traverse child categories that are not leaf until it reaches the leaf categories
if(empty($LeafCategory))
{
echo "this is not a leaf category";
$CategoryInfo = GetCategoryInfo($CategoryID);

$child_count = count($CategoryInfo);
$child_i = 1;
while($child_i <= $child_count)
{
$Category = $CategoryInfo[$child_i];
$CategoryID = $Category['CategoryID'];
$CategoryName = $Category['CategoryName'];
$LeafCategory = $Category['LeafCategory'];
echo " Child category :: $CategoryID\n $CategoryName\n $LeafCategory\n <br>";

$child_i++;
}

}
$top_i++;
}






How to ROT13 encode in Python3?

The Python 3 documentation has rot13 listed on its codecs page.



I tried encoding a string using rot13 encoding:



import codecs
s = "hello"
os = codecs.encode( s, "rot13" )
print(os)


This gives a unknown encoding: rot13 error. Is there a different way to use the in-built rot13 encoding? If this has been removed in Python 3, why is it still listed in Python3 documentation?





Remote ssh connection from within Emacs

Several questions, including this one, discuss aspects relating to ssh connections from within Emacs. I haven't found an answer to my question though: How can I ssh into a remote machine from within Emacs?



I do not wish to edit a file on the remote machine from within Emacs. I am aware of M-x shell which opens a shell on my local machine and I am aware of using TRAMP to edit a file over ssh on the remote machine. However, neither of these relate to this question.



(Instead of voting to close, maybe migrate the question to another site.)



Edit: Related discussion here.





OnTouch method in OnDraw

I need to set an onTouch method to the rect that I have set up but I dont know how to do this in an OnDraw method. this but I dont know how here my code, Thanks for the help!



public class Tab3 extends View implements OnTouchListener
{
int x1, x2, y1, y2;
Rect Rect = new Rect();
public Tab3(Context context, AttributeSet attrs)
{
super (context, attrs);
x1 = 0;
x2 = 100;
y1 = 0;
y2 = 100;

}

@Override
protected void onDraw(Canvas canvas)
{
// TODO Auto-generated method stub
super.onDraw(canvas);


Rect.set(x1, y1, x2, y2);

Paint blue = new Paint();
blue.setColor(Color.BLUE);
canvas.drawRect(Rect, blue);
}

@Override
public boolean onTouch(View v, MotionEvent event)
{

return false;
}
}




Jquery .Click event only triggering first button in the loop

Jquery .click event only triggers the first button! I loop through data and add buttons to each on my html page and would like each button to trigger a dialog box when clicked.. But only the first one works! the rest seem to have no click event.



$(document).ready(function () {



$("#btn_comment").click(function () {

$("#createComment").dialog(
{
modal: true,
height: 300,
width: 500,
buttons: {
"Create a Comment": function () {
var post_id = $(this).parent().attr("id");
var desc_to_create = $("#txtComment").val();
$.post("CreateComment", { "id": "", "username": "x", "post_id": post_id, "description": desc_to_create, "created": "" }, function (t) {

alert("Thank you! Your comment has been updated!!");
location.reload();

})


},
"Cancel": function () {
$(this).dialog("close");
}
}
}
);
})


})





    <tr id='<%= Html.Encode(item.id) %>'>
<td>

<%: Html.ActionLink("Details", "Details", New With {.id = item.id})%> |
<a href="javascript://" class="delete_btn">Delete</a>

</td>
<%-- <td>
<%: item.id %>
</td>
<td>
<%: item.username %>
</td>
<td>
<%: item.title %>
</td>--%>
<td>
<%: item.description %>
</td>
<td>
<input id="btn_comment" type="button" value="Add a Comment" />
</td>
<td>
<div id="new_comment"></div></td>
</tr>

<% Next%>




Bash script with graphical menus

Good day,



I have been writing simple bash scripts for a while now, and I was wondering how I could implement simple menus and, if possible, use menus with color.



In the past, I have written simple C applications that use ncurses (http://en.wikipedia.org/wiki/Ncurses) and would like to (if possible) have menus in my bash script where the user can use the up/down arrows to select items in a list, and go back/forth through a series of yes/no/cancel prompts.



I am familiar with setting up colored text in bash, so there's a start (eg: http://webhome.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html), so the only requirement left at this point is to see if bash has these capabilities. I would prefer to avoid having to code an application in C/C++ for this, as I would like to be able to edit it on the fly.



Thank you all in advance.





Creating dropdown in rails erb error

Originally I had my view setup like:



<%= render layout: 'form' do |f| %>

<% for holiday in Holiday.find(:all) %>
<label class="checkbox">
<%= check_box_tag "user[holiday_ids][]", holiday.id, @user.holidays.include?(holiday) %>
<%= holiday.name %>
</label>


Which rendered a list of 8 "interests". However, I needed 3 out of these 8 to have unique div id's in order to have a jquery show/hide function to display divs below them when checked. To do this i just took the html rendered by the above erb code and pasted it into my view and manually modified it to work with the jquery statement (pasted below).. My question is that in these div's that are displayed by the jquery i need to have a dropdown which is populated by another model in my app.. How can i achieve this? I attempted the statement in the first div but its causing the following error (code taken from my _form partial):



undefined method `map' for nil:NilClass
Extracted source (around line #12):

9: </ul>
10: </div>
11: <% end %>
12: <%= yield f %>
13:
14: <div class="actions">
15: <%= f.submit "Continue" %>


Here is the HTML + erb statement i am attempting..



<%= render layout: 'form' do |f| %>
<div id="checkbox">
<label class="checkbox">
<input id="user_holiday_ids_" name="user[holiday_ids][]" type="checkbox" value="2" />
Valentine Day
</label>
</div>
<div style="display:none;">
<%= select_tag 'Interests', options_for_select(@interests) %>
</div>

<div id="checkbox">
<label class="checkbox">
<input id="user_holiday_ids_" name="user[holiday_ids][]" type="checkbox" value="4" />
Mothers Day
</label>
</div>
<div style="display:none;">
Whatever you have to capture here<input type="text" id="foo2" />
</div>
<label class="checkbox">
<input id="user_holiday_ids_" name="user[holiday_ids][]" type="checkbox" value="7" />
Thanksgiving
</label>
<div id="checkbox">
<label class="checkbox">
<input id="user_holiday_ids_" name="user[holiday_ids][]" type="checkbox" value="5" />
Father's Day
</label></div>
<div style="display:none;">
Whatever you have to capture here<input type="text" id="foo3" />
</div>
<label class="checkbox">
<input id="user_holiday_ids_" name="user[holiday_ids][]" type="checkbox" value="3" />
Easter
</label>

<label class="checkbox">
<input id="user_holiday_ids_" name="user[holiday_ids][]" type="checkbox" value="6" />
Halloween
</label>
<label class="checkbox">
<input id="user_holiday_ids_" name="user[holiday_ids][]" type="checkbox" value="8" />
Christmas
</label>?
<% end %>




Trouble installing ruby 1.9.3

I am looking to install ruby 1.9.3. I currently have ruby 1.9.2 installed



Mac Os X
Xcode Version 4.3.2
I have dumped all the previous version of Xcode



I have read a ton of articles and I tried out the steps that are detailed in http://stackoverflow.com/a/9651747/1392225



This is the error that I have



ruby-1.9.3-p125 - #fetching 
ruby-1.9.3-p125 - #extracted to /Users/kai/.rvm/src/ruby-1.9.3-p125 (already extracted)
WARN: Patch 'xcode-debugopt-fix-r34840.diff' not found.
ruby-1.9.3-p125 - #configuring
ruby-1.9.3-p125 - #compiling
ERROR: Error running 'make ', please read /Users/kai/.rvm/log/ruby-1.9.3-p125/make.log
ERROR: There has been an error while running make. Halting the installation.


The error log seems to point to this



compiling readline.c
readline.c: In function 'username_completion_proc_call':
readline.c:1499: error: 'username_completion_function' undeclared (first use in this function)
readline.c:1499: error: (Each undeclared identifier is reported only once
readline.c:1499: error: for each function it appears in.)
make[2]: *** [readline.o] Error 1
make[1]: *** [ext/readline/all] Error 2
make: *** [build-ext] Error 2


Any ideas?





C# WinForm 3.5 DataGridView Column Autosize Margin

I have a C# 3.5 WinForm project, and I can't find where to adjust Margin used for a DataGridView's Header AutoSize.



AutoSizeColumnsMode is set to None.
I can resize the column larger or smaller, then double click to AutoResize, and it pops to this width, using the margin illustrated by my awesome paint skills:



DataGridView Header Margin
How can I adjust the margin used?





Datatable does not contain a definition for AsEnumerable using LinqBridge1.1 in C#2.0

i'm trying to use linq in c#2.0(linqbridge) to search for a patient name in my database,
but i'm getting the following errors:
System.Data.Datatable does not contain a definition for AsEnumerable()
System.Data.Datatable does not contain a definition for CopyToDataTable()



I added the linqBridge.dll reference to my project.
And i'm using:



using System.Linq;



            List<string> names = name.Split(' ').ToList();
SqlConnection con = new SqlConnection(m_connection_string);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM PATIENT", con);
DataSet ds = new DataSet();
da.Fill(ds);

var query =
from pat in ds.Tables["PATIENT"].AsEnumerable().Where(c => names.All(val => c.PAT_SEARCH_NAME.Contains(val)))
select pat;

DataTable table = query.CopyToDataTable();


What am i doing wrong?
I already read that this version of LinqBridge(1.1) does not contain this methods..
Is there a way to solve this?



Thanks.