Thursday, April 12, 2012

How can I get all locations in a list that are not equal to a value(without using a for loop)?

okay not sure if there is a better way than I'm already doing. Right now I have a list(int[]) that has a over 10,000 values that equal 0 in it and I'm looking for only the non-zero items.



My current approach is just to do a for loop and capture all the non-zeros but I do this a lot, and profiling shows its taking a large amount of my cpu time(since I'm doing this so often). Is there a way I can get the same results without the expensive cpu process(since out 10,000 items, only less than 100 will be non-zeros)?



Here's an example of my data:



int[] list = {0,0,0,1,0,10 }
int[] list_names = {a,b,c,d,e,f}


All I need to ultimately do is use these two lists to create another two lists with only the non-zero values and their names(so D=1 and F=10). I've seen some solutions where I need to sort the results before it works but thats a problem because if I sort the data list then I cannot identify its name.



Is this possible and is there a faster way compared to a for loop?



Sorry I should mention that this large lists remain in my program for processing and I'm trying to do this to reduce the memory footprint of them. I have a queue of a few hundred million of these lists being stored in their entirety when all I really need is the non-zero values, so doing this to save memory(which seems to be working) but I'm also trying not to take a bit hit on the cpu to get it to that point(since I need the cpu for my processing).





Is it possible to gather the number of bluetooth devices around Android device

I would like to get the number of bluetooth devices located around an android device and then store that number in the SQLite database. Is it possible to easily get that number?





Local Variable Declaration Issue

Im getting the following error:




Cannot use local variable 'dob' before it is declared




Here is my implementation



public class Person
{
...
public string dob { get; set; }
...

public int getAge()
{
DateTime origin = DateTime.Parse(dob);
return DateTime.Today.Year - origin.Year;
}

public string getFormattedDoB()
{
DateTime origin = DateTime.Parse(dob);
string dob = origin.ToString("d");
return dob;
}
}


I am not sure what to make of this because it is complaining about it's use of dob in getFormattedDoB() but not in getAge() which comes before it. If anyone could shed some light on this that would be great





CI 2 - Language class and models

I noticed an odd issue and I can't seem to find anything to explain it.



on one of my models i add an error output message to alert that a record is not available, but when it outputs, i get no text, just a blank page.



Now the language tags are valid, the only thing i can figure is that the language file isn't meant to be used on a model, if thats the case I don't see that being explained anywhere.



I hope someone can help me get in the right direction on this, if i have to just set it to false and handle the message on the ui, I'll do that, but prefer not to.



Thanks.



EDIT:



here is what a quick code snipplet that should help:



//fetch topic data.
$this->db->select('id, Name, Description, Level');
$this->db->from('groups');
$this->db->where('id', $gid);
$query = $this->db->get();
$GroupData = $query->row();

//see if we have any records to show.
if($query->num_rows() > 0) {
$this->setId($GroupData->id);
$this->setName($GroupData->Name);
$this->setDescription($GroupData->Description);
$this->setLevel($GroupData->Level);
} else {
//no record was found, throw an error.
show_error($this->lang->line('invalidgid').'<hr />File:'.__FILE__.'<br />Line:'.__LINE__, 500, $this->lang->line('error'));
log_message('error', 'invalid GroupID was provided.'); //log error in error log.
}




IIS 7 URL Rewrite - 403 Error

I know this question has been asked before, but I haven't found an answer to what I'm running into. I'm trying to redirect a domain (not a sub-domain) to a sub-folder. I'm running IIS 7 and I created a URL rewrite rule like this:



<rule name="subfolder" enabled="true" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll">
<add input="{HTTP_HOST}" pattern="^(www\.)?domain.com?" />
<add input="{PATH_INFO}" pattern="^subfolder" negate="true" />
</conditions>
<action type="Rewrite" url="/subfolder/{R:0}" />
</rule>


With the rule off, I can navigate to a page like http://domain.com/subfolder/index.htm. With it on, I get a 403 error when I try to navigate to http://domain.com/index.htm.



403 - Forbidden: Access is denied.

You do not have permission to view this directory or page using the credentials that you supplied.


How do I fix this?





Using UIScrollview to access 4 different views

This seems like it should be pretty straight forward but im really stuck. I basically want to start the app and it goes to the center view, where the user can swipe up down left or right to access four different views. the picture pretty much sums it up. I will make the text in the picture "swipe up for view 1" "swipe down for ....." buttons also that achieve the same thing as the swiping but I dont want to ask for too much so if anyone can help me out and show me how to program what Im looking for I would much appreciate it.Main Menu views Of app



I was able to get it to be just one massive view but I realized that I want it to jump to every different view, not scroll and be half way there. and when I tried to make cgrect frames it was very confusing to keep it all in order.





combine js array's

pretty simple question, can't quite fig. it out.



I have 2 js array's that I need to combine into a new array, based on sub_key.



var items = [
Object {
OBJECTID=1,
Name="COMMAND B",
ID="AR0xx",
sub_key="1000"
},
Object {
OBJECTID=2,
Name="95TH PCT",
ID="AR0xx",
sub_key="1001"
},
Object {
OBJECTID=379,
Name="dummy4",
ID="AR0xx",
sub_key="9999"
}
];

var subitems = [
Object {
OBJECTID=787,
ID="AR0xx",
sub_key=1000,
Long_Name = foo
},
Object {
OBJECTID=789,
ID="AR0xx",
sub_key=1001,
Long_Name = "bar"
},
Object {
OBJECTID=1,
ID="AR0xx",
sub_key=1001,
Long_Name="baz"
},
Object {
OBJECTID=788,
ID="AR0xx",
sub_key=1001,
Long_Name="buzzz"
}
];


I'd like to create an array like so, which just combines the above 2, based on sub_key



var data = [
COMMAND B=["foo"],
95TH PCT=["bar","baz","buzz"]
dummy4=[]
];


Here's what I tried but it doesn't work... i think i'm close?? thanks for any help!



data = [];
for (var key in items){
var o = items[key];
//data.push(o.Name);
for (var subkey in subitems){
subo = subitems[subkey];
if (o.sub_key == subo.sub_key){
data[o.Name].push(subo.Long_Name)
}
}
}




unable to disable future date in jquery datepicker

My application requires that the date picker should display the calender body on click, select date today's date being active and future date deactivated... i am new in jquery and it has disturbed me for a month. assist please. I am able to display the datepicker and choose any date upto 2030, but i need the calender to be active upto today's date or current date only.
thanks in advance.



my calender to be displayed..



<table id="calenderTable" class="">
<tbody id="calenderTableHead">
<tr>
<td colspan="4" align="center">
<select onChange="showCalenderBody(createCalender(document.getElementById('selectYear').value,
this.selectedIndex, false));" id="selectMonth">
<option value="0">Jan</option>
<option value="1">Feb</option>
<option value="2">Mar</option>
<option value="3">Apr</option>
<option value="4">May</option>
<option value="5">Jun</option>
<option value="6">Jul</option>
<option value="7">Aug</option>
<option value="8">Sep</option>
<option value="9">Oct</option>
<option value="10">Nov</option>
<option value="11">Dec</option>
</select>
</td>
<td colspan="2" align="center">
<select onChange="showCalenderBody(createCalender(this.value,
document.getElementById('selectMonth').selectedIndex, false));" id="selectYear">
</select>
</td>
<td align="center">
<a href="#" onClick="closeCalender();"><font color="#003333" size="+1">X</font></a>
</td>
</tr>
</tbody>
<tbody id="calenderTableDays">
<tr style="">
<td>Sun</td><td>Mon</td><td>Tue</td><td>Wed</td><td>Thu</td><td>Fri</td><td>Sat</td>
</tr>
</tbody>
<tbody id="calender"></tbody>
</table>


the date field is as below:



    <tr>
<td>effected date</td>
<td>
<input type="text" name="eff_date" class="required" id="eff_date"><a href="#" onClick="setYears(1947, 2030);
showCalender(this, 'eff_date');" class="" id="calender">
<img src="Calender/calender.png"></a>
</td>
</tr>




How to create user control groupbox object in VC++?

I am trying to extend the groupbox class to a temp_groupbox class which includes two radiobuttons inside the groupbox. I am facing two problems. First, I don't know how to set the two lines of event handler code for the radiobuttons because I think I should set them in the window form class NOT in this temp_groupbox class. Am I right? Second, I can only see a groupbox (small, not the size that I set in this class. Basically, there is something wrong) in my window form and I cannot see any radiobutton (even if I delete those two lines of even handler code.) Please help



        public ref class temp_groupbox: public GroupBox
{
public: temp_groupbox(int a, int b, String ^groupboxname){

// Create and initialize a GroupBox and two RadioButton controls.
GroupBox^ groupBox1 = gcnew GroupBox;
RadioButton^ radioButton1 = gcnew RadioButton;
RadioButton^ radioButton2 = gcnew RadioButton;

// Add the RadioButtons to the GroupBox.
groupBox1->Controls->Add( radioButton1 );
groupBox1->Controls->Add( radioButton2 );

groupBox1->Location = System::Drawing::Point(a, b);
groupBox1->Size = System::Drawing::Size(800, 800);
groupBox1->TabIndex = 0;
groupBox1->TabStop = false;

radioButton1->Name = L"radioButton1";
radioButton2->Name = L"radioButton2";


radioButton1->Size = System::Drawing::Size(85, 17);
radioButton2->Size = System::Drawing::Size(85, 17);

radioButton1->Location = System::Drawing::Point(130, 40);
radioButton2->Location = System::Drawing::Point(40, 140);

radioButton1->TabIndex = 1;
radioButton1->TabStop = true;

radioButton2->TabIndex = 2;
radioButton2->TabStop = true;

radioButton1->UseVisualStyleBackColor = true;
????radioButton1->CheckedChanged += gcnew System::EventHandler(this, radioButton1_CheckedChanged);
radioButton2->UseVisualStyleBackColor = true;
????radioButton2->CheckedChanged += gcnew System::EventHandler(this, radioButton2_CheckedChanged);
groupBox1->SuspendLayout();
groupBox1->ResumeLayout(false);
groupBox1->PerformLayout();
}



};// end ref class


The following is the way that I call the temp_groupbox class form my window form class



            temp_groupbox^ Temp1 = gcnew  temp_groupbox(120, 130, "asd");
Controls->Add(Temp1);
SuspendLayout();
ResumeLayout(false);




Disable/enable jQuery click event to avoid multiple POST requests

I have a webpage that shows some news, and a button that when is clicked shows older news doing an AJAX call to the server.



The problem is that if people click too fast, the request is done twice, therefore, I receive 2 equal responses.




  • #mas-noticias-footer is the id of the button that displays older news


  • .noticias-list is the class asigned to each new, using .length I get
    the number of news displayed, and POST that number to a PHP file that
    does a SQL query using LIMIT(numItems,3) (I get 3 news at a time).


  • #noticias-display is the ul that contains the news




This is the code



$(document).ready(function() {
$("#mas-noticias-footer").on('click',function() {
var numItems = $('.noticias-list').length;
$.ajax({
type: "POST",
url: "mas-noticias.php",
data: "num-noticias="+numItems,
success: function(data) {
$('#noticias-display').append(data);
}
});
});
});


I have tried using off() and unbinding the event at the beginning of the on callback, to avoid the multiple calls (that works), the problem is when I delegate the event using on() at the end of the callback, I can't make it work.





Powerbuilder Datawindow Password Encrypt

I have a Tabular User Maintenace Window that uses Datawindow Select / Update.



I need to encrypt the password saved on the MSSQL Database.



I have a function f_decrypt for Powerbuilder and for dbo.



How can I use dw.Update() to encrypt the password?





On Post, a drop down list SelectList.SelectedValue is null

My model is as follows:



public class testCreateModel
{
public string s1 { get; set; }
public SelectList DL { get; set; }

public testCreateModel()
{
Dictionary<string, string> items = new Dictionary<string, string>();
items.Add("1", "Item 1");
items.Add("2", "Item 2");
DL = new SelectList(items, "Key", "Value");
}
}


My initiating actions is:



    public ActionResult testCreate()
{
testCreateModel model = new testCreateModel();
return View(model);
}


My Razor view (irrelevant parts deleted) is:



@model Tasks.Models.testCreateModel

@using (Html.BeginForm()) {
<fieldset>
<legend>testCreateModel</legend>

<div class="editor-label">
@Html.LabelFor(model => model.s1)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.s1)
</div>

<div class="editor-label">
Select an item:
</div>
<div class="editor-field">
@Html.DropDownList("dropdownlist", (SelectList)Model.DL)
</div>

<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}


The post back action is:



    public ActionResult testCreate(testCreateModel model, FormCollection collection)
{
if (ModelState.IsValid)
{
Console.WriteLine("SelectedValue: ",model.DL.SelectedValue);
Console.WriteLine("FormCollection:", collection["dropdownlist"]);
// update database here...
}
return View(model);
}


On post back, model.DL.SelectedValue is null. (However, the selected item can be obtained from FormCollection, but that is besides the point). The DL object is still properly populated otherwise, Immediate Window output as follows:



model.DL
{System.Web.Mvc.SelectList}
base {System.Web.Mvc.MultiSelectList}: {System.Web.Mvc.SelectList}
SelectedValue: null
model.DL.Items
Count = 2
[0]: {[1, Item 1]}
[1]: {[2, Item 2]}
model.DL.SelectedValue
null


Q1: How can I make use of the SelectedValue property instead?



Now, if in the Razor view I change the name of the Html SELECT tag to DL (ie same as the property name in the model):



@Html.DropDownList("DL", (SelectList)Model.DL)


I get an exception:



No parameterless constructor defined for this object. 
Stack Trace:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +199
System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult
...


Q2: Why?



Thanks.





Popup window in Java when a USB port scans some input

I have an application written on Java running on the machine (Linux/Windows). I want to make this application run like a background application so that it does not interrupt while using other applications in the system. Now I want to popup a screen and show some buttons (to do some tasks based on the selection) when a QR Code is scanned using a scanned attached to the USB port. When this scanning happens my Java application that initiates the popup screen is running hidden in the background.



--Edit--

I have used key listeners to identify the bar code scanning and pull out information from database based on what is scanned. But while scanning my application, was open. So I attached the action listeners in the AWT level so that the key strokes/scanning is caught and taken care off. But now in the current case I wont be having any windows active. SO I NEED TO CAPTURE THE SCANNED INPUT INTERNALLY IN OS LEVEL.





iPhone init method issue

I created a property for the NSArray which creates a getter/setter. I know Apple recommends using the instance variable in the init and dealloc method. I'm trying to figure what to do in the following code.



(1) Do I need an extra release statement? Wouldn't array have a retain count of 2 then 1 with the dealloc, leave a leak. Or would autorelease take care of this?



(2) Is there some way in xCode or instruments to follow a specific variable to see its retain count going through the process.



@property (nonatomic, retain) NSArray *array;

@synthesize arrary = _array;

- (id)initWithNibName:(NSString *)nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil
initWithArray:(NSArray *)array
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {

_array = [[NSArray alloc] initWithArray:array];

}
return self;
}

- (void)dealloc
{
[_array release];

[super dealloc];
}




Store Checkbox value to array list

How do i store the value of a checked checkbox to an array list and display it in a list./..say Checkbox1 = "Apple"......so far i have this"



public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {



            if (checkBox1.isChecked()) {


//my problem is below here: I can't seem to add the value of it not the id and store it in list



                pubsList.add(pub3);
pub3=Integer.toString(checkBox1.getSelectedItem());




ASP.NET MVC3: can Action accept mulitple model parameters?

For example:



class MyContoller
{
[MyCustomAttribute]
public ActionResult MyAction(ModelX fromRequest, ModelY fromSession, ModelZ fromCookie)
{
string productId = fromRequest.ProductId;
string userId = fromSession.UserId;
string cultureName = fromCookie.CultureName;
}
}


Reason:



I don't want to visit Request, Session and HttpContext in the controllers, and the default idea of MVC3 which passing models to actions is very great.



I want the number of parameters of MyAction is easy to change. For example, if I add a new parameter, the system will try to look for values in Request, Session or Cookies by the name or type of the parameter (I think custom ModelBinders may be required for cookie values) and pass the filled model to my action. I don't have to write extra code.



Can the custom attribute (MyCustomAttribute in the example) accomplish this idea?



Best regards,
Zach@Shine





Animating a div with CSS on hover

I'm trying to animate a div on hover using CSS3's @keyframes rule. The code for the animation is at the very bottom of this page (right after the generously marked "HERE BE ANIMATION" comment ASCII art). That includes the @keyframes rule, the div, and the div:hover. The page where I wanted this animation is right here. For some reason, the animation doesn't work; this is the first time I've tried using CSS animation, so there's probably some novice mistake somewhere.





How to generate a 3-digit random number in xCode for iPhone

The thing is that I need use a code like this, but it doesn't work with char variable. Can you help me to write the code, or show how we can do it with an array?



Code:



char numeroMaquina[0] = arc4random() % 9;

switch(numeroMaquina[0]) {
case 0:
numeroMaquina[0] = 1;

break;
case 1:
numeroMaquina[0] = 2;

break;
case 2:
numeroMaquina[0] = 3;

break;
case 3:
numeroMaquina[0] = 4;

break;
case 4:
numeroMaquina[0] = 5;

break;
case 5:
numeroMaquina[0] = 6;

break;
case 6:
numeroMaquina[0] = 7;

break;
case 7:
numeroMaquina[0] = 8;

break;
case 8:
numeroMaquina[0] = 9;

break;
}

int numeroMaquina2 = arc4random() % 9;
switch(numeroMaquina2) {
case 0:
numeroMaquina2 = 1;

break;
case 1:
numeroMaquina2 = 2;

break;
case 2:
numeroMaquina2 = 3;

break;
case 3:
numeroMaquina2 = 4;

break;
case 4:
numeroMaquina2 = 5;

break;
case 5:
numeroMaquina2 = 6;

break;
case 6:
numeroMaquina2 = 7;

break;
case 7:
numeroMaquina2 = 8;

break;
case 8:
numeroMaquina2 = 9;

break;
}


int numeroMaquina3 = arc4random() % 9;
switch(numeroMaquina3) {
case 0:
numeroMaquina3 = 1;

break;
case 1:
numeroMaquina3 = 2;

break;
case 2:
numeroMaquina3 = 3;

break;
case 3:
numeroMaquina3 = 4;

break;
case 4:
numeroMaquina3 = 5;

break;
case 5:
numeroMaquina3 = 6;

break;
case 6:
numeroMaquina3 = 7;

break;
case 7:
numeroMaquina3 = 8;

break;
case 8:
numeroMaquina3 = 9;

break;
}




How to grab string between two keywords in PHP

Not sure if this has been answered before - how can I grab string between two keywords?



For instance the string between a 'story' and a '?',



http://mywebsie.com/hello/blog/story/archieve/2012/5/?page=1    
http://mywebsie.com/blog/story/archieve/2012/4/?page=1
http://mywebsie.com/blog/story/archieve/2012/?page=4


I just want,



story/archieve/2012/5/
story/archieve/2012/4/
story/archieve/2012/


EDIT:



If I use parse_url,



$string = parse_url('http://mywebsie.com/blog/story/archieve/2012/4/?page=1');
echo $string_uri['path'];


I get,



/blog/story/archieve/2012/4/


but I don't want to include 'blog/'





Encoding json data as x-www-form-urlencoded

I am trying to POST wih curl some data. The source data is in JSON, but I want to post with content-type application/x-www-form-urlencoded. I am trying to do it like this:



curl -X POST $URL --data-urlencode "@$data.json" --header "Content-Type: application/x-www-form-urlencoded"


This is data.json:



{
"action" : "deploy_from_scratch_with_bundle",
"pusher" : { "email" : "my@email.com" },
"ref" : "refs/heads/master",
"repo_choice" : "LOCAL"
}


But this is not working: urlparse.parse_qs (python) is complaining about ValueError.



The received data (before parse_qs) is:



%7B%0A%20%20%22action%22%20%20%20%20%20%20%3A%20%22deploy%5Ffrom%5Fscratch%5Fwith%5Fbundle%22%2C%0A%20%20%22pusher%22%20%20%20%20%20%20%3A%20%7B%20%22email%22%20%3A%20%22my%40email%2Ecom%22%20%7D%2C%0A%20%20%22ref%22%20%20%20%20%20%20%20%20%20%3A%20%22refs%2Fheads%2Fmaster%22%2C%0A%20%20%22repo%5Fchoice%22%20%3A%20%22LOCAL%22%0A%7D%0A


What am I doing wrong here?





Script Error when linking from ASP.Net Application to Linkedin

sorry if this is a simple problem, I have tried looking for a solution but cannot find anything. I'm having trouble linking to a specific Linkedin profile from my Asp.Net site.



I am using the Imagemap server control, but when the link is clicked a script error occurs "Microsoft JScript runtime error:'WebTrack' is Undefined".



If I click ignore or continue the page still loads, just want to make sure it's not going to cause any problems when the site is published.



Just to confirm I just need to link to the page.



Many Thanks





Suggestion of UML diagram

I need to draw a diagram but I am not sure what sort of diagram that is appropriate for my application.



It is a mobile application that contains:




  1. Splash (as welcoming scree)

  2. Main Menu Screen (Which contains)

    • Gallery

    • Settings

    • Map

    • Help




The Gallery has contain all the images/photos that is stored on the device.



Can anyone suggest what sort of UML that is appropriate for this application? Is it Use Case Diagram? or Sequence Diagram?



Thanks in advance.





Need xpath to locate 2 buttons with almost same properties for using in Selenium automation script

Both these buttons have almost similar ID (the number on the ID may change and so is not reliable)
Both have same classes
They both reside under the same parent
Except for the span nothing is different



All the UI elements of the application I am trying to locate and build events on Using Selenium are similar to the below piece...



Can anyone please suggest how I can locate these buttons preferable with xpath?



<div id="button-1749" class="x-btn x-box-item x-toolbar-item x-btn-default-toolbar-  small x-noicon x-btn-noicon x-btn-default-toolbar-small-noicon x-item-disabled x-disabled x-btn-disabled x-btn-default-toolbar-small-disabled" style="margin: 0pt; left: 1563px; top: 0px;">
<em id="button-1749-btnWrap" class="">
<button id="button-1749-btnEl" class="x-btn-center" autocomplete="off" role="button" hidefocus="true" type="button" aria-disabled="true" disabled="">
<span id="button-1749-btnInnerEl" class="x-btn-inner" style="">Delete Selected</span>
<span id="button-1749-btnIconEl" class="x-btn-icon x-hide-display">&nbsp;</span>
</button>
</em>
</div>
<div id="button-1750" class="x-btn x-box-item x-toolbar-item x-btn-default-toolbar-small x-noicon x-btn-noicon x-btn-default-toolbar-small-noicon" style="margin: 0pt; left: 1654px; top: 0px;">
<em id="button-1750-btnWrap" class="">
<button id="button-1750-btnEl" class="x-btn-center" autocomplete="off" role="button" tabindex="1" hidefocus="true" type="button">
<span id="button-1750-btnInnerEl" class="x-btn-inner" style="">New Title</span>
<span id="button-1750-btnIconEl" class="x-btn-icon x-hide-display">&nbsp;</span>
</button>
</em>
</div>




Heap allocate a 2D array (not array of pointers)

I am writing C code and I would like to heap allocate 512*256 bytes. For my own convenience I would like to be able to access the elements with the syntax array[a][b]; no arithmetic to find the right index.



Every tutorial I see online tells me to create an array of pointers that point to arrays of the rows I want in my array. This means that each subarray needs to be malloc'd and free'd individually. I am interested in a solution that only requires on call to malloc and call to free.(Thus all elements are contiguous) I think this is possible because I will not be constructing a jagged array.



I would appreciate if anyone could share the syntax for declaring such an array.





Using a generic style as base vs custom user control

I'm creating a resource dictionary to my application, where I'll have some "icon+text" buttons. Since they will all look the same (except for the icon and the text), I've created a generic style to serve as base to the others:



<!-- Generic ActionButtonStyle -->
<Style x:Key="ActionButtonStyle" TargetType="{x:Type Button}">
<!-- some setter properties -->
<Setter Property="ContentTemplate" Value="{DynamicResource ButtonDataTemplate}"/>
</Style>
<DataTemplate x:Key="ButtonDataTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="24" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Source="{Binding Source}"
Stretch="Uniform"
Grid.Column="0"
Margin="2"/>
<TextBlock Text="{Binding text}"
TextWrapping="Wrap"
Grid.Column="1"
Margin="2"
VerticalAlignment="Center"/>
</Grid>
</DataTemplate>


And I have some images for the icons:



<!-- Icons -->
<ImageSource x:Key="textToSpeech">Images/GreyIcons/TextToSpeech.png</ImageSource>
<ImageSource x:Key="play">Images/GreyIcons/Play.png</ImageSource>
<ImageSource x:Key="playSound">Images/GreyIcons/PaySound.png</ImageSource>
.
.
.
.
<ImageSource x:Key="group">Images/GreyIcons/Goup1.png</ImageSource>


And I'd like to create individual styles for each button (corresponding to each icon). Something like this:











I know that this doesn't work.. How should I do it? Should I create a custom user control for the generic button? The text will be binding to an object in my Model, and so will the command (to an action).





mysql order by with limit

I have a query where I want to get the 20 most popular locations from a table, and then order them alphabetically. I'm wondering if there's a cleaner or more efficient way to do this?



SELECT city FROM (SELECT city, count(*) AS cnt FROM locations GROUP BY city ORDER BY cnt DESC LIMIT 20) s ORDER BY city;




Only seeing 1 object out of an array of 3 in XNA

Can anyone see where I am going wrong here.



I have a CameraObject class (its not a camera, simply the Model of a box to represent a "camera") that has a Model and a Position. It also has the usual LoadContent(), Draw() and Update() methods.
However, when I draw the array of Models, I only see 1 model on the screen (well, there might be 3 but they might all be in the same location)?



The Draw() method for the CameraModel class looks like this:



public void Draw(Matrix view, Matrix projection) 
{
transforms = new Matrix[CameraModel.Bones.Count];
CameraModel.CopyAbsoluteBoneTransformsTo(transforms);

// Draw the model
foreach(ModelMesh myMesh in CameraModel.Meshes)
{
foreach (BasicEffect myEffect in myMesh.Effects)
{
myEffect.World = transforms[myMesh.ParentBone.Index];
myEffect.View = view;
myEffect.Projection = projection;

myEffect.EnableDefaultLighting();
myEffect.SpecularColor = new Vector3(0.25f);
myEffect.SpecularPower = 16;
}
myMesh.Draw();
}
}


Then in my Game1 class I create an array of CameraObject objects:



CameraObject[] cameraObject = new CameraObject[3]; 


Which I Initialize() - so each new object should be at +10 from the previous object



for (int i = 0; i < cameraObject.Length; i++) 
{
cameraObject[i] = new CameraObject();
cameraObject[i].Position = new Vector3(i * 10, i * 10, i * 10);
}


And finally Draw()



Matrix view = camera.viewMatrix; 
Matrix projection = camera.projectionMatrix;

for (int i = 0; i < cameraObject.Length; i++)
{
cameraObject[i].Draw(view, projection);
}


Where view and projection are from my Camera() class which looks like so:



viewMatrix = Matrix.Identity; 
projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), 16 / 9, .5f, 500f);


But I only see 1 object drawn to the screen? I have stepped through the code and all seems well but I cant figure out why I cant see 3 objects?



Can anyone spot where I am going wrong?





Zend Auth - Using two tables

I'm currently developing a website in Zend Framework wich uses Zend_Auth. The current design of the database is the following:




  • users - id / email

  • users_props - id - user_id - prop_name - prop_value



However, the current Zend_Auth_Adapter_DbTable uses only one table, as where I have to tables and need to join them.



How on earth can I do this? As far as i'm concerned, there are three options:




  1. I somehow create a (mysql) view

  2. I change the design so the users table contains both username/password

  3. I rewrite the Zend_Auth_Adapter_DbTable to a Custom_Auth_Adapter_DbTabe



Can anyone point me out what the best practise is?



Thanks in advance :)





Has anyone tried using ZooKeeper?

I was currently looking into memcached as way to coordinate a group of server, but came across Apache's ZooKeeper along the way. It looks interesting, and Yahoo uses it, so it shouldn't be bad, but I'd never heard of it before, so I'm kind of skeptical. Has anyone else given it a try? Any comments or ideas?





Variable In Link Redirect JavaScript

I want to make something so that a variable is shown in a redirect, but I can't seem to figure out how. I want the page to redirect to google.com/'name' (the variable) for my website, but whatever I try doesn't seem to work. This may seem a little confusing, if so, leave a comment, don't answer. Here's the code:



<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
{
alert("Hi + name + !");
window.top.location.replace("http://www.google.com/" + name ");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_prompt()" value="Show prompt box" />
</body>
</html>