Monday, 30 September 2013

To find out the minimum amount of fuel

To find out the minimum amount of fuel

There is a ship which can carry $K$ creatures at a time. There are two
types of creatures $D$ and $U$. They are to be carried from one side of
the river to the other side, with the constraint being $D$ can never be
greater than $U$ on either side of the river. The amount of fuel needed
for each trip from one side to the other side is $X$. I have to find the
minimum amount of fuel needed to carry all creatures across to the other
side. How to solve this?
example- $3, 3, 2, 10$ Output-$110$

Wifi on Lenovo N581 blocks other wifi clients

Wifi on Lenovo N581 blocks other wifi clients

I have a problem with the wifi on my new Lenovo IdeaPad N581: the wifi
works after installing the additional drivers, but when I switch it on all
other computers connected to our wifi router (the french freebox), I have
no internet access anymore.
If I boot windows it works fine. The card is a broadcom BCM4313 802.11bgn,
the driver shown by lsmod is cfg80211 or wl.

How to know the current Xpath?

How to know the current Xpath?

I am currently using a Xpath Reader to go through my xml file.
What i need is a method for knowing the current Xpath. After some search i
can't find online documentation on the methods of Xpath Reader..
Does anyone know of it?
XmlTextReader xtr = new XmlTextReader(bodyPart.Data);
XPathCollection xc = new XPathCollection();
//the code between theese two lines is not here due to its size,
//but it fills the XpathCollection
XPathReader xpr = new XPathReader(xtr, xc);
while (xpr.ReadUntilMatch())
{
//What i need is a method, to be called in the reading cycle,
//that when called returns the current Xpath.
}
Does anyone knows of it?
Thank you

Filtered arrays and since() functionality in ember-data

Filtered arrays and since() functionality in ember-data

I have a backend resource that contains user activities and in the
application I would like to present activities based on a single day's
worth of activities. I have an ArrayController called ActivitiesController
defined in the router like this:
this.resource('activities', { path: '/activities/:by_date' }, function() {
this.route('new');
});
The REST API provides the following GET method:
GET /activities/[by_date]
So far this looks pretty symmetrical and achievable but I'm running into
two problems:
Parameterized array find. Typically a parameterized route would be
serviced by a ObjectController but in this case the by_date parameter
simply reduces/filters the array of activities but it's still an array
that's returned. I'm not sure how to structure this in the model hook in
the ActivitiesRoute so that its effectively doing a "findAll" rather than
expecting a singular resultset.
Since functionality. As there is a reasonable network cost in bringing
back these arrays of activities I would like to minimize this as much as
possible and the REST API supports this by allowing for a since parameter
to be passed along with the date of the last request. This way the server
simply responds with a 304 code if no records have been updated since the
last call and if there are new records only the new records are returned.
Is there anyway to get this "out of the box" with ember-data? Does this
require building a custom Adaptor? If so, are there any open source
solutions that are available?

Sunday, 29 September 2013

consuming REST API with C#

consuming REST API with C#

I'm very new to C# and want to learn how to make HTTP requests. I want to
start really simple, although that is currently evading me. I want to just
perform a GET on, say, google.com. I created a command line application,
and have this code. Not sure at all which usings are required.
I tested it by writing to the console, and it doesn't get past the
response. Can somebody please clue me in? I'm looking to do some simple
curl type stuff to test an existing API. Thank you for your help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
namespace APItest
{
class testClass
{
static void Main(string[] args)
{
string url = "http://www.google.com";
Console.WriteLine(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response =
(HttpWebResponse)request.GetResponse();
Console.ReadKey();
}
}
}

How to compare a string with a string in pointer in c++

How to compare a string with a string in pointer in c++

I am implementing linked list in c++. In that am trying to compare a data
stored in the node with a string. Here is my code:
String f;
cin>>f;
if(strcmp(temp->data,f)==0)
{ cout<<"same"; }
else
{ cout<<"not same"; }
Here is my error:
"assignment1.cc", line 160: Error: Cannot cast from std::string to const
char*.
"assignment1.cc", line 160: Error: Cannot cast from std::string to const
char*.
How to compare those two strings?

JOIN 3 tables for search

JOIN 3 tables for search

I have 3 tables: Session, Film and Vendor
Session.FilmID
Film.VendorID
Vendor.VendorName
I want to include the VendarName in the search.
Here's what I have:
sql ="SELECT SessionID, Identifier, SessionType.SessionTypeName, Film.*,
Vendor.*,
CameraID, Date FROM Session "
sql = sql + "JOIN SessionType USING (SessionTypeID) "
sql = sql + "JOIN Film USING(FilmID) "
sql = sql + "JOIN Vendor ON Film.VendorID = Vendor.VendorID "
sql = sql + "WHERE Session.Identifier LIKE ('%" + search + "%') OR "
sql = sql + "Session.Notes LIKE('%" + search + "%') OR "
sql = sql + "SessionType.SessionTypeName LIKE ('%" + search + "%') "
sql = sql + "Film.Vendor.VendorName LIKE ('%" + search + "%') "
sql = sql + "ORDER BY Identifier,SessionType.SessionTypeName"
What am I doing wrong?

How to ask webcam to auto focus with Unity3D

How to ask webcam to auto focus with Unity3D

Friends, Currently, i am working on some Augmented reality mobile App with
Unity3D. The performance is impacted by the image quality. Is there some
way to ask webcam to auto focus with Unity3D? Thank you~

Saturday, 28 September 2013

Jumping / Jitter for DIV Hover state

Jumping / Jitter for DIV Hover state

I just cant seem to fix this issue where on hover, the DIV expands and
then shrinks giving a "jumpy" or "jitter" look.
I have a list which will be for images and I want the hover state to be an
block that is 10px less than its parent;
Here is my fiddle:
Here is my code;
HTML
<div id="container">
<li class="item w2 h2"> <div class="inner"></div></li>
<li class="item w2 h2"> <div class="inner"></div></li>
<li class="item w2 h2"> <div class="inner"></div></li>
<li class="item w2 h2"> <div class="inner"></div></li>
<li class="item w2 h2"> <div class="inner"></div></li>
<li class="item w2 h2"> <div class="inner"></div></li>
</div>
CSS - the inner class is the one with the hover
#container {
padding: 5px;
margin: 0 auto;
border: 2px solid black;
}
.item {
display:block !important;
list-style:none;
float: left;
background: #CCC;
margin: 5px;
width: 50px;
height: 50px;
}
.item.w2 { width: 300px; }
.item.h2 { height: 200px; }
.inner {
background:#fff;
background: rgba(255, 255, 255, 1);
position: absolute;
top: 10px;
left: 10px;
bottom: 10px;
right: 10px;
margin:0;
padding:0;
text-align: center;
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);
opacity: 0;
-webkit-transition: opacity .4s ease-in-out;
-moz-transition: opacity .4s ease-in-out;
-ms-transition: opacity .4s ease-in-out;
-o-transition: opacity .4s ease-in-out;
transition: opacity .4s ease-in-out;
}
.inner:hover {
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=95)";
filter: alpha(opacity=95);
opacity: .95;
z-index:1;
}
/* no transition on .isotope container */
.isotope .isotope-item {
/* change duration value to whatever you like */
-webkit-transition-duration: 1s;
-moz-transition-duration: 1s;
transition-duration: .6s;
}
.isotope .isotope-item {
-webkit-transition-property: -webkit-transform, opacity;
-moz-transition-property: -moz-transform, opacity;
transition-property: transform, opacity;
opacity:.5;
}
Consequently the "jumpy" or "jitter" disappears when there is no
-transition such as ease-in-out or opacity.
I appreciate anyone who has a look! any suggestions would be great this is
a huge learning curve for me :)

Is it possible to upgrade Apache to 2.2.25 in Webmin/CentOS 5.9?

Is it possible to upgrade Apache to 2.2.25 in Webmin/CentOS 5.9?

I've been tasked with upgrading to Apache 2.2.25 because of PCI compliance
issues. I tried but only managed to break Apache.
Does anyone know if it's even possible to upgrade to Apache 2.2.25 under
this server config? Or do we need to upgrade to CentOS 6x to achieve this?
Trying to test it over the weekend, so any help would be greatly appreciated!

Current time - past time = human readble time

Current time - past time = human readble time

I have got a function form form SC to get human readable time.
function human_time ($time)
{
$time = time() - strtotime($time); // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
And I have time as string: 2013-09-28 20:55:42
when I call this function human_time('2013-09-28 20:55:42')
then it return nothing, why ? I have added strtotime in above function.
Please tell me what is wrong.

insert multiple arrays to database

insert multiple arrays to database

I am creating a multiple choice quiz and I don't know how to insert
multiple arrays to database. Please help. Here is my code.
<?php
if(isset($_POST['btnCreate'])) {
$inQuestion = array($_POST['inQuestion']);
$inAnswer = array($_POST['inAnswer']);
$inA = array($_POST['inA']);
$inB = array($_POST['inB']);
$inC = array($_POST['inC']);
$inD = array($_POST['inD']);
$inLesson = $_POST['inLesson'];
$inQuizNo = $_POST['inQuizNo'];
$sql = "SELECT * FROM lessons WHERE title='$inLesson'";
$query = mysql_query ($sql);
$row = mysql_fetch_assoc($query);
$lessonID = $row['lessonID'];
foreach(array_combine($_POST['inQuestion'], $_POST['inAnswer']) as
$question => $answer) {
$sql = "INSERT INTO `test` (question, answer, A, B, C, D,
lessonID, quizNo) VALUES ('$question', '$answer', '$_POST[A]',
'$_POST[B]', '$_POST[C]', '$_POST[D]', '$lessonID',
$inQuizNo)";
$query = mysql_query( $sql );
}
}
?>

Friday, 27 September 2013

Two web_view on two activities

Two web_view on two activities

i just start to learn Android_programing i want to set two or more links
at main_layout and the web_view to another activity (or layout what is
easier) so i start this
public void onCreate(Bundle savedInstanceState) {
final Context context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.buttonUrl);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
Intent intent = new Intent(context, Web.class);
startActivity(intent);
}
});}
public void onCreate1(Bundle savedInstanceState){
final Context context1 = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.buttonUrl1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(context1, Activity1.class);
startActivity(i);
}
});
}
}

What to do when borrowing open-source code? [on hold]

What to do when borrowing open-source code? [on hold]

In this program I am developing I have borrowed open-source code from some
authors who have said that the code was free to use/distribute/edit. But I
don't know if it is customary to write down the author's name somewhere or
if I should write I borrowed code from something.com or ... . I would be
happy if someone could help me because I am about to deploy my program but
am unsure how I should give credit to the respectful owners, or if I even
should give credit? Please help!

My datetime isn't formatted correctly, what have I done wrong?

My datetime isn't formatted correctly, what have I done wrong?

I'm a bit of a python newbie but can't find anything about this specific
problem.
from Tkinter import *
from datetime import datetime
username = []
password = []
userClass = []
userDB = []
def loadLoginWindow():
global loginWindow, indicator, usernameEntry, passwordEntry,
indicatorLabel, submitButton, loadButton
loginWindow = Tk()
loginWindow.wm_title("Project 001: Login")
loginWindow.wm_resizable(0,0)
indicator = StringVar()
usernameLabel = Label(loginWindow, text = "username:")
usernameLabel.grid(row = 0, column = 0)
usernameEntry = Entry(loginWindow)
usernameEntry.grid(row = 0, column = 1)
passwordLabel = Label(loginWindow, text = "password:")
passwordLabel.grid(row = 1, column = 0)
passwordEntry = Entry(loginWindow, show = "*")
passwordEntry.grid(row = 1, column = 1)
indicatorLabel = Label(loginWindow, textvariable = indicator)
indicatorLabel.grid(row = 2, column = 0, columnspan = 2)
submitButton = Button(loginWindow, text = "submit", command = login)
submitButton.grid(row = 3, column = 0, columnspan = 2)
loginWindow.mainloop()
def loadUserPanelWindow():
global userPanelWindow, headerGIF, spacerGIF, mainLabelText, usrnm
mainLabelText()
userPanelWindow = Tk()
userPanelWindow.wm_title("Project 001: User Panel")
userPanelWindow.wm_resizable(0,0)
headerGIF = PhotoImage(file = "image/userPanel/header.gif")
spacerGIF = PhotoImage(file = "image/userPanel/spacer.gif")
headerLabel = Label(userPanelWindow, image = headerGIF)
headerLabel.grid(row = 0, column = 0, columnspan = 6)
numberButton = Button(userPanelWindow, text= "Number")
numberButton.grid(row = 1, column = 0)
algebraButton = Button(userPanelWindow, text= "Algebra")
algebraButton.grid(row = 1, column = 1)
dataButton = Button(userPanelWindow, text= "Data")
dataButton.grid(row = 1, column = 2)
shapeButton = Button(userPanelWindow, text= "Shape")
shapeButton.grid(row = 1, column = 3)
spaceButton = Button(userPanelWindow, text= "Space")
spaceButton.grid(row = 1, column = 4)
measuresButton = Button(userPanelWindow, text= "Measures")
measuresButton.grid(row = 1, column = 5)
spacerLabel = Label(userPanelWindow, image = spacerGIF)
spacerLabel.grid(row = 2, column = 0, columnspan = 6)
mainLabel = Label(userPanelWindow, text = mainLabelText, justify =
LEFT)
mainLabel.grid(row = 3, column = 0, columnspan = 6, sticky = W)
spacerLabel = Label(userPanelWindow, image = spacerGIF)
spacerLabel.grid(row = 4, column = 0, columnspan = 6)
settingsButton = Button(userPanelWindow, text= "Settings")
settingsButton.grid(row = 5, column = 3)
helpButton = Button(userPanelWindow, text= "Help")
helpButton.grid(row = 5, column = 4)
logoutButton = Button(userPanelWindow, text= "Logout", command =
logout)
logoutButton.grid(row = 5, column = 5)
userPanelWindow.mainloop()
def login():
global index, usrnm, psswrd
index = 0
usrnm = usernameEntry.get()
psswrd = passwordEntry.get()
while index < len(username):
if username[index] == usrnm:
if password[index] == psswrd:
loginWindow.destroy()
loadUserDB()
updateUserDBDates()
loadUserPanelWindow()
break
else:
indicator.set("Password doesn't exist!");
break
else:
index = index + 1
else:
indicator.set("Username doesn't exist!");
def logout():
global index, usrnm, psswrd
index = 0
usrnm = 0
psswrd = 0
userPanelWindow.destroy()
loadLoginDB()
loadLoginWindow()
def saveData():
global username, password, userClass
with open("username.txt", "w") as fWUsername:
fWUsername.write("\n".join(str(x) for x in username))
with open("password.txt", "w") as fWPassword:
fWPassword.write("\n".join(str(x) for x in password))
with open("userclass.txt", "w") as fWUserClass:
fWUserClass.write("\n".join(str(x) for x in userClass))
def loadLoginDB():
global username, password, userClass
with open("username.txt", "r") as fRUsername:
usernameNoStrip = fRUsername.readlines()
username = map(str.strip, usernameNoStrip)
with open("password.txt", "r") as fRPassword:
passwordNoStrip = fRPassword.readlines()
password = map(str.strip, passwordNoStrip)
with open("userClass.txt", "r") as fRUserClass:
userClassNoStrip = fRUserClass.readlines()
userClass = map(str.strip, userClassNoStrip)
def loadUserDB():
global usrnm, userDB
with open("userDB/" + usrnm + ".txt", "r") as fRUserDB:
userDBNoString = fRUserDB.readlines()
userDB = map(str.strip, userDBNoString)
def updateUserDBDates():
global userDB, currentDate, previousDate, changeInDateStr
index = 0
index2 = 0
currentDate = datetime.strptime(userDB[0], "%Y-%m-%d")
previousDate = datetime.strptime(userDB[1], "%Y-%m-%d")
changeInDate = currentDate - previousDate
changeInDateStr = str(changeInDate)
def mainLabelText():
global mainLabelText, usrnm, currentDate, previousDate,
changeInDateStr
mainLabelText = "Welcome, " + usrnm + "!" + "\n" + "You were last
logged on at " + str(previousDate) + "." + " This was " +
changeInDateStr + " ago!"
loadLoginDB()
loadLoginWindow()
In the userDB I have this
2013-09-25
2013-09-20
but in the mainLabel I get this
you were last logged on at 2013-09-20. This was 5 days, 0:00:00 ago!`
the expected output was
you were last logged on at 2013-09-20. This was 5 days, ago!
Any help would be GREATLY appreciated, thank you for having patience.

Highlight all occurences of string - case insensitive

Highlight all occurences of string - case insensitive

On this page I want to search for a word in the text and highlight all
occurences. If, for example, I look for "front end" than I want all
occurences of "Front end" to be highlighted. With the code below I do
highlight them but the occurences's upper case character is also replaced.
Can you fix this? here's my code:
this makes jQuery contains case insensitive
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
and this is the code that highlights by replacing
$('input[value="Zoeken"]').click(function(){
$('.section').html(function (i, str) {
yellowspan = new RegExp('<span style="background-color: #FFFF00">'
,"g");
empty = "";
return str.replace(yellowspan, empty);
});
$('.section').html(function (i, str) {
endspan = new RegExp("</span>" ,"g");
empty = "";
return str.replace(endspan, empty);
});
var string = $('input[placeholder="Zoeken"]').val();
$('.section:contains("' + string + '")').each(function(index, value){
$(this).html(function (i, str) {
simpletext = new RegExp(string,"gi");
yellowtext = "<span style='background-color: #FFFF00'>" +
string + "</span>";
return str.replace(simpletext, yellowtext);
});
});
});

Current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction

Current transaction cannot be committed and cannot support operations that
write to the log file. Roll back the transaction

I know that there are other questions with the exact title as the one I
posted but each of them are very specific to the query or procedure they
are referencing.
I manage a Blackboard Learn system here for a college and have direct
database access. In short there is a stored procedure that is causing
system headaches. Sometimes when changes to the system get committed
errors are thrown into logs in the back end, identifying a stored
procedure known as bbgs_cc_setStmtStatus and erroring out with The current
transaction cannot be committed and cannot support operations that write
to the log file. Roll back the transaction.
Here is the code for the SP, however, I did not write it, as it is a stock
piece of "equipment" installed by Blackboard when it populates and creates
the tables for the application.
USE [BBLEARN]
GO
/****** Object: StoredProcedure [dbo].[bbgs_cc_setStmtStatus] Script
Date: 09/27/2013 09:19:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[bbgs_cc_setStmtStatus](
@registryKey nvarchar(255),
@registryVal nvarchar(255),
@registryDesc varchar(255),
@overwrite BIT
)
AS
BEGIN
DECLARE @message varchar(200);
IF (0 < (SELECT count(*) FROM bbgs_cc_stmt_status WHERE registry_key =
@registryKey) ) BEGIN
IF( @overwrite=1 ) BEGIN
UPDATE bbgs_cc_stmt_status SET
registry_value = @registryVal,
description = @registryDesc,
dtmodified = getDate()
WHERE registry_key = @registryKey;
END
END
ELSE BEGIN
INSERT INTO bbgs_cc_stmt_status
(registry_key, registry_value, description) VALUES
(@registryKey, @registryVal, @registryDesc);
END
SET @message = 'bbgs_cc_setStmtStatus: Saved registry key [' +
@registryKey + '] as status [' + @registryVal + '].';
EXEC dbo.bbgs_cc_log @message, 'INFORMATIONAL';
END
I'm not expecting Blackboard specific support, but I want to know if there
is anything I can check as far as SQL Server 2008 is concerned to see if
there is a system setting causing this. I do have a ticket open with
Blackboard but have not heard anything yet.
Here are some things I have checked:
tempdb system database:
I made the templog have an initial size of 100MB and have it auto grow by
100MB, unrestricted to see if this was causing the issue. It didn't seem
to help. Our actual tempdb starts at 4GB and auto grows by a gig each time
it needs it. Is it normal for the space available in the tempdb to be
95-985 of the actual size of the tempdb? For example, right now tempdb has
a size of 12388.00 MB and the space available is 12286.37MB.
Also, the log file for the main BBLEARN table had stopped growing because
it reached its maximum auto grwoth. I set its initial size to 3GB to
increase its size, but for some reason every time I check off
"unrestricted growth", the radio button goes back to restricting the
growth to 2GB.
Thanks for any advice.

Animating child back to original position

Animating child back to original position

I am using the animate() method to send my TextView to the
bottom-most-right of the layout using the following code:
move.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int xValue = container.getWidth() - myView.getWidth();
int yValue = container.getHeight() - myView.getHeight();
myView.animate().x(xValue).y(yValue);
}
});
This does the trick but I am sort of lost on restoring the element back to
its original position. I did try the following, but it didn't work:
public class MainActivity extends Activity {
Button fadeIn, fadeOut, move, moveBack;
TextView myView;
LinearLayout container;
float originalX , originalY;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fadeIn = (Button)findViewById(R.id.fadeIn);
fadeOut = (Button)findViewById(R.id.fadeOut);
move = (Button)findViewById(R.id.move);
moveBack = (Button)findViewById(R.id.moveBack);
myView = (TextView)findViewById(R.id.myView);
originalX = myView.getX();
originalY = myView.getY();
Log.i("X and Y", ""+originalX+" "+originalY);
container = (LinearLayout) findViewById(R.id.container);
fadeIn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
myView.animate().alpha(1);
}
});
fadeOut.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
myView.animate().alpha(0);
}
});
move.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int xValue = container.getWidth() - myView.getWidth();
int yValue = container.getHeight() - myView.getHeight();
myView.animate().x(xValue).y(yValue);
}
});
moveBack.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
myView.animate().x(originalX).y(originalY);;
}
});
}
}
The following gives me with the 0,0 position on X and Y. Help please.

Forwarding http to https in node.js express app using EBS & ELB environment

Forwarding http to https in node.js express app using EBS & ELB environment

I am using the following to redirect all http requests to https requests.
app.get('*', function(req, res, next) {
//http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#x-forwarded-proto
if (req.headers['x-forwarded-proto'] != "https") {
res.redirect('https://' + req.get('host') + req.url);
} else {
next();
}
});
It is causing a redirect loop. How can I redirect properly without looping?

Thursday, 26 September 2013

connecting python code from rdesktop full screen

connecting python code from rdesktop full screen

I have a python code running in my linux machine. Through that code i am
connecting to a remote desktop using rdesktop. I am using pygtk. I have
key event in the python code. But that is not working when the rdesktop is
in full screen mode. How to solve this. Please tell me. Thank you in
anticipation.

Wednesday, 25 September 2013

GWT 2.5 -- Custom EditTextCell -- Not Allowing Space bar to enter

GWT 2.5 -- Custom EditTextCell -- Not Allowing Space bar to enter

I have created Custom Cell by extending EditTextCell , I couldnt enter
"SPACE BAR" in the EditTextCell, If i do like that, the row celltable got
selected by leaving focus from Text cell Edit.

Thursday, 19 September 2013

Writing 2nd dimension to Range from a 2D variant without looping in VBA

Writing 2nd dimension to Range from a 2D variant without looping in VBA

I have a variant variable, and pass the following range values to it like so.
Option Base 1
Dim varEmployees As Variant
varEmployees = Range("A1:B5").Value
This 2D variant now has Employee IDs in the 1st dimension and Employee
names in the 2nd. So we get something like the following.
varEmployees(1,1) = 1234 varEmployees(1,2) = John Doe
varEmployees(2,1) = 5678 varEmployees(2,2) = Jane Smith
varEmployees(3,1) = 9012 varEmployees(3,2) = Mary Major
varEmployees(4,1) = 3456 varEmployees(4,2) = Judy Stiles
varEmployees(5,1) = 7890 varEmployees(5,2) = Richard Miles
I want to write the 2nd dimension only back to a range without using a
loop but when I use the following code...
Range("D1:D5") = varEmployees
I only get the 1st dimension as shown under Actual Results but what I want
is my Desired Results (only the 2nd dimension).
Actual Results Desired Results
-------------- ---------------
1234 John Doe
5678 Jane Smith
9012 Mary Major
3456 Judy Stiles
7890 Richard Miles
Is there a way to do this or is there a rule about variant arrays that I
am not aware of.

Is there a decent alternative to "pip bundle"?

Is there a decent alternative to "pip bundle"?

I use pip bundle for my production systems, and today I was greeted with
the following disheartening message:
###############################################
## ##
## Due to lack of interest and maintenance, ##
## 'pip bundle' and support for installing ##
## from *.pybundle files is now deprecated, ##
## and will be removed in pip v1.5. ##
## ##
###############################################
My servers auto-scale and build themselves out automatically, but I've
been burned before by relying on PyPi being available. Instead, I use pip
bundle and commit the .pybundle file to the source git repo. This means I
only need to rely on a single source for building my servers.
With pip bundle going away (and who knows when) I need an alternative
method to use - are there any suggestions or similar methods of packaging
up dependencies for production distribution?
Thanks!

Database and Application how to integrate for deployment

Database and Application how to integrate for deployment

So I have a big question to ask:
How do I make a Java application (using eclipse) use a database that will
pack it into the jar file, or how do I get the database to ship with the
jar file, without having to install a mysql server such as phpMyAdmin,
workbench, etc?
I have an application that uses a database, now how do I extract that
database and the application, so that it I can compile it into an exe
file, and copy that one installer file, and when I install the application
on another machine, I dont need to install a phpMyAdmin, mysql server, etc
to run the database, and jdk for the program to run and all these
unnecessary programs that the end user will NOT DO.
Please advise on how to do this, and best possible solutions.
This is also what I need to do to finish off my major project for the year
for school (Grade 11).
Thanks in advance!

Bing maps How to set a pin on a map (url)?

Bing maps How to set a pin on a map (url)?

I have all the code, the only thing that missing for me is how to put a
pushpin in that url:
http://www.bing.com/maps/default.aspx?v=2&cp=50.22599~50.81103&lvl=10
My pushpin link is: http://s8.postimg.org/8uuikcaw1/pin.png
I want to make something like this:
http://www.bing.com/maps/default.aspx?v=2&cp=50.22599~50.81103&lvl=10&pushpin=http://s8.postimg.org/8uuikcaw1/pin.png
Or if bing maps has their pushpin, it's also good. Just want to get a
static image with a map and a pushpin on it, can someone help me?
Thanks :)

PHP function varying parameters

PHP function varying parameters

I couldn't find about my issue on google and SO. Hope, i can explain you.
You'll understand when looked following function:
function get_page($identity)
{
if($identity is id)
$page = $this->get_page_from_model_by_id($identity);
elseif($identity is alias)
$page = $this->get_page_from_model_by_alias($identity);
}
My used function:
get_page(5); // with id
or
get_page('about-us'); // with alias
or
get_page(5, 'about-us'); // with both
I want to send parameter to function id or alias. It should be only one
identifier.
I dont want like function get_page($id, $alias)
How can i get and know parameter type with only one variable. Is there any
function or it possible?

How to Convert String to Date without knowing the format of String?

How to Convert String to Date without knowing the format of String?

In My Application I am reading the date parameter from user in the String
format.
After reading the parameter, I need to convert the String to *desired date
format.*
Desired format = YYYY-MM-DD HH:MM:SS
Input String can be in any format.
Eg: 2013/09/19 14:21:07 OR 2013-09-19 14:21:07
Irrespective of the format Obtained, I need to convert it to desired
format. How to achieve this?
I saw few snippet where,
SimpleDateFormat formatter = new SimpleDateFormat("YYYY/MM/DD HH:MM:SS");
Date dt = formatter.parse("2013/09/19 14:21:07");
SimpleDateFormat desiredFormatter = new
SimpleDateFormat("YYYY-MM-DD HH:MM:SS");
desiredFormatter .format(dt);
The above snippet works only when we know the input format to parse the
String. But In my case I dont know the input format. So I was thinking to
use directly format method without parsing.
Is this possible?

Java - Dinamically add items to JCheckBox

Java - Dinamically add items to JCheckBox

Is there a way to add dynamically items to a jCheckBox in Java as in
jComboBox we use addItem method?

Wednesday, 18 September 2013

PHP - Remove items from an array with given parameter

PHP - Remove items from an array with given parameter

I've searched around and I found some similar questions asked, but none
that really help me (as my PHP abilities aren't quite enough to figure it
out). I'm thinking that my question will be simple enough to answer, as
the similar questions I found were solved with one or two lines of code.
So, here goes!
I have a bit of code that searches the contents of a given directory, and
provides the files in an array. This specific directory only has .JPG
image files named like this:
Shot01.jpg Shot01_tn.jpg
so on and so forth. My array gives me the file names in a way where I can
use the results directly in an tag to be displayed on a site I'm building.
However, I'm having a little trouble as I want to limit my array to not
return items if they contain "_tn", so I can use the thumbnail that links
to the full size image. I had thought about just not having thumbnails and
resizing the images to make the PHP easier for me to do, but that feels
like giving up to me. So, does anyone know how I can do this? Here's the
code that I have currently:
$path = 'featured/';
$newest = new RecursiveIteratorIterator(new
RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS));
$array = iterator_to_array($newest);
foreach($array as $fileObject):
$filelist = str_replace("_tn", "", $fileObject->getPathname());
echo $filelist . "<br>";
endforeach;
I attempted to use a str_replace(), but I now realize that I was
completely wrong. This returns my array like this:
Array
(
[0] => featured/Shot01.jpg
[1] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03.jpg
)
I only have 3 images (with thumbnails) currently, but I will have more, so
I'm also going to want to limit the results from the array to be a random
3 results. But, if that's too much to ask, I can figure that part out on
my own I believe.
So there's no confusion, I want to completely remove the items from the
array if they contain "_tn", so my array would look something like this:
Array
(
[0] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
)
Thanks to anyone who can help!

ItemFileWriteStore vs dojo.store.Memory?

ItemFileWriteStore vs dojo.store.Memory?

I'm using dojo 1.6 and I wanna create a store to connect to a grid;
however, in dojo 1.6 only exists two ways with ItemFileWriteStore and
store Memory which of these two is the best ?
I'm working with spring 2.5 for the controller.

Sum elements of static array in compile-time

Sum elements of static array in compile-time

I'm trying to sum &#8203;&#8203;the elements of a static array in
compile-time via templates:
#include <type_traits>
template<size_t idx, int* arr>
struct static_accumulate :
std::integral_constant<size_t, arr[idx] + static_accumulate<idx -
1, arr>::value>
{ };
template<int* arr>
struct static_accumulate<0, arr> : std::integral_constant<size_t, 0>
{ };
constexpr int arr[9] = {1, 2, 3,
4, 5, 6,
7, 8, 9};
int main()
{
std::cout<<static_accumulate<8, arr>::value;
}
but I got this compile-error:
error: could not convert template argument 'arr' to 'int*'
compiler - gcc 4.7.
How I can avoid it?

Get href from link and attach it to another link

Get href from link and attach it to another link

I actually have working code for this problem, but I think it's probably
not very efficient. I think I could probably combine it into one, but my
knowledge of JS is still limited enough that I'm not sure how to do it.
The problem: I have 3 slider divs on the homepage. Each div has an H5
title tag wrapped in an unpopulated <a> tag. So I need to pull the href
from each div's .slideshow-button and apply it to the h5 tag. (Weird
problem, but just go with it.)
The (inefficient? but working) solution:
$('.homepage-slideshow:first-child .title-controls a').attr('href',
$('.homepage-slideshow:first-child .slideshow-buttons a').attr('href'));
$('.homepage-slideshow:nth-child(2) .title-controls a').attr('href',
$('.homepage-slideshow:nth-child(2) .slideshow-buttons a').attr('href'));
$('.homepage-slideshow:nth-child(3) .title-controls a').attr('href',
$('.homepage-slideshow:nth-child(3) .slideshow-buttons a').attr('href'));
Can I combine these into one, so I don't have to do it 3 separate times?

Number of Documents in a LotusNotes view

Number of Documents in a LotusNotes view

I am working to integrate a Lotus Notes database into Salesforce using
Java. However, I am running into trouble for one portion of the project.
The data I am returning to Salesforce gets initialized in the form of:
String[][] result = new String[id.length][field.length] id and field are
both arrays that I create inside Salesforce and pass as parameters to the
Java that handles the web service.
Most views I've had to access have had a unique id to query off of, so it
was fairly simple to populate an array of ids that I want to query Lotus
Notes with.
However, I ran into a problem with one View that does not have anything
available as a unique id. Our solution was to concatenate two columns
together as the SF id and just pull the whole View back. This means I just
need to tell the results array to be View.NumberOfRecords instead of
id.length in size. But for the life of me, I cannot find how
programatically pull the number of documents in a view.
Any help on this would be greatly appreciated. I am new to Lotus Notes,
and hope to not have to use it again if figuring out simple tasks like
this require so much effort.

PHP redirecting external site and POST json

PHP redirecting external site and POST json

I am integrating a registration with another website. The other website
posts my site some registration data in json, to a registration page on my
site and prepopulating the fields. I take the user through the
registration, then on success redirect back to the original site. This
redirect is supposed to post some info back, in json format, the user ID
etc. I'm not sure how to go about redirecting back and posting this data?
I'd rather not use a JS form submit.
Any help appreciated.

Mysql query to select only one unique name on a criteria

Mysql query to select only one unique name on a criteria

I have a table like this.
+------------+-------------+--------------+
| name | hobby | hobby number |
+------------+-------------+--------------+
| jack | sport | 1 |
| marco | skydiving | 3 |
| alfonso | driving | 1 |
| marco | learning | 2 |
| jack | dancing | 2 |
+------------+-------------+--------------+
I want to use sql select statement to select only one unique name.
The table I want may look like this:
+------------+-------------+--------------+
| name | hobby | hobby number |
+------------+-------------+--------------+
| jack | sport | 1 |
| marco | learning | 2 |
| alfonso | driving | 1 |
+------------+-------------+--------------+
What should sql query be?
Thank you in advance.

Failed to run Mac app after being installed by PackageMaker-based installer, Only fails on muli-user accounts machine

Failed to run Mac app after being installed by PackageMaker-based
installer, Only fails on muli-user accounts machine

I have prepared mono app bundle. Then I used Apple's PackageMaker for
making an installer. The installer has post script which fixes some
relative symbolic links inside the bundle folder after being installed in
/Applications.
I've tested the installer on a fresh Mac machine with single admin user
account. The installer succeeds and the installed application runs
perfectly.
The problem is : When I created another admin account on that machine. The
installation succeeded, but the installed bundle's icon has an overly
(stop or Blocked) icon! And when I run my applications, it refuses and the
flowing message pops up :
You can't open the application XYZ because it is not supported on this
type of Mac.
I knew it SHOULD be supported, as it was working on "this type of mac" !
tried to modify user/group and permissions for the bundle in PackageMaker
window, but not luck.
Can you please clarify my confusion regarding this message and the
suggested solution ?

Tuesday, 17 September 2013

Carousel Animation in android

Carousel Animation in android

please see below screen i have tried to implement this animation using
overflow as we Carousel but i am not getting same as represented in
screen. if any body have done this type of animation please send me the
code snippet,

Thanks in advance.

How to use Wysiwyg upload files for my button in magento

How to use Wysiwyg upload files for my button in magento

I want add a custom button in admin form, use files manager of Wysiwyg
editor. But i can't find anything sad about that.
Please give me any solutions if you have.
Thanks.

Optimization suggestions

Optimization suggestions

Here is a haskell code which calculates number of swaps done in insertion
sorting. It is supposed to be O(n*log n). But it is too slow, even for
input range of ~40000 it takes more than 15 seconds to give the answer
whereas sorting the same input takes much less time (around 0.4 seconds).
I would have expected a slowdown due to all the Map operations but never
this order of magnitude.
import Data.List (sort,foldl')
import Data.Map (Map)
import qualified Data.Map as M
greaterThan :: Int -> Map Int Int -> Int
greaterThan k = M.fold (+) 0 . snd . M.split k
swaps :: [Int] -> Int
swaps = fst . foldl' with (0,M.empty)
where
with (s,m) v = (s + greaterThan v m, m')
where
m' = M.alter f v m
f Nothing = Just 1
f (Just c) = Just $ c + 1

Accessing JSON on server side (asp.net)

Accessing JSON on server side (asp.net)

I have a web app that we're still stuck in asp.net 2.5 with. We've started
using some newer technology with our front end, including loading some of
our data into JSON objects and passing them around the application using
localStorage. It's working really great.
In the future we're going to change our ASP.NET web form architecture into
ah HTML5/JQuery front and Web API back end. So we're trying to write for
that future while still being constrained to our old web form post backs
and business objects. So right now we're posting from our search form to
our search result page web form and we'll be calling a method from our
business object to grab and return search results.
The criteria object we pass in has 20 or so values and a couple of
collections (product line ID's, category ID's, etc..). So it's a slightly
complicated object. In the old form we grabbed values from the controls,
validated them, and passed them in using the asp.net controls, it was a
single form solution. Our new solution has a search form and a results
page. We're passing our values from form to form in a JSON object in
internal storage. I can't really get to that from server side so I also
stashed the values in a hidden field on the form that I can grab on the
server side when I POST to the results page (eventually we'll call an API
from the new form using ajax). So now that I can see the data, how do I
parse and work with a JSON object in the code behind of asp.net. I need to
load the 20 or so search criteria values and iterate through the ID
collections (Guid and int) to load them into the same criteria object.
This object is then passed in as the search methods parameter and search
results will come back. Not sure how to manipulate the json on the server
side.

C# find time zone and time from given string of timestamp

C# find time zone and time from given string of timestamp

I need to parse the time and get the timezone from a string like the
following,
Timestampt = 2013-09-17T14:55:00.355-08:00
From the above string, I should be able to get time as 2:55pm and timezone
as EST (-8:00 mean est I guess)
Can anyone please let me know how the above can be done

Sunday, 15 September 2013

Add multiple google schema ConfirmAction

Add multiple google schema ConfirmAction

I am working on a project that would require some authorized users to
'Approve' or 'Reject' a request.
I would like these actions to be performed right from the user's inbox.
Is it possible to add more than one ConfirmAction that will be disabled
once one of them is clicked. If yes, kindly provide a sample markup.

End call method - iOS development

End call method - iOS development

What's the method that gets called when the user press the end call button
while making a phone call and how to use it in my app? Thank you

Get the width of img inside ul li a

Get the width of img inside ul li a

I'm trying to get the width and height of an image inside of a ul li a as
followed:
<ul class="gallery">
<li><a href="#"><img src="#"></a></li>
<li><a href="#"><img src="#"></a></li>
<li><a href="#"><img src="#"></a></li>
<li><a href="#"><img src="#"></a></li>
</ul>
I've done this jquery code as followed:
$(document).ready(function(){
$(".gallery").find("li a").each(function() {
alert($(this).find("img").width() + 'x' + $(this).find("img").height());
});
});
and for some reason I keep getting 0x0, all I want is the width and height
of each of the image inside the ul li a.
I've also read that I need to do the following:
$('.gallery li a img').load(function() {
var $img = $(this);
$img.parent().width($img.width());
});
because the document.ready is fired before the image.load, but It still
not working.
Any help will be appreciated. Thank you.

Head (not face) detection and tracking in kinect depth maps

Head (not face) detection and tracking in kinect depth maps

I am looking for the best way to track human heads (not faces) in a stream
of depth maps from the kinect using OpenCV. I want to use only depth data,
no color info. Any ideas? I've tried using Haar cascade classifiers for
upper body provided in OpenCV but they do not give robust performance.
Thanks

Protect files with a password

Protect files with a password

I need to password protect files (with C#). files can be in any format
pdf, txt, xml, excel, word.
I found out that i could use various 3rd party libraries to password lock
PDF files, but not all the other files available out there.
Can someone please direct me with the correct approach to solve this.
In brief when an user double clicks on a file he/she should be asked to
enter the correct password to view its content.
Sorry i don't have any code to demonstrate my findings.

How to create a cmd file to run jars?

How to create a cmd file to run jars?

I have literally tried everything to try and make my jar files executable
by double clicking. But i have come to the conclusion that either I need
some major help because my java installation has a problem, or I need to
create a .cmd file to automatically run them properly. The code in the
file would be like this:
java -jar myfile.jar
What would i replace myfile.jar with so that windows puts in the file
extension of what i'm trying to open? Thanks.

converting bash script to zsh

converting bash script to zsh

I want to translate this bash-script intro a zsh-script. Hence I have no
experience with this I hope I may get help here:
bash script:
SCRIPT_PATH="${BASH_SOURCE[0]}";
if([ -h "${SCRIPT_PATH}" ]) then
while([ -h "${SCRIPT_PATH}" ]) do SCRIPT_PATH=`readlink
"${SCRIPT_PATH}"`; done
fi
pushd . > /dev/null
cd `dirname ${SCRIPT_PATH}` > /dev/null
SCRIPT_PATH=`pwd`;
popd > /dev/null
What I already know is that I can use SCRIPT_PATH="$0"; to get the path
were the script is located at. But then I get errors with the "readlink"
statement.
Thanks for your help

Saturday, 14 September 2013

Is there a way to automatically extend a content block while typing?

Is there a way to automatically extend a content block while typing?

I want to know if there is a way to automatically extend content block by
typing or do I have to manually do it block by block?

New to PHP, I need to sort a large 2 dimensional array by values in the 2nd dimension

New to PHP, I need to sort a large 2 dimensional array by values in the
2nd dimension

I have an array of sales data in an array, and I want to be able to sort
the 1st dimension of the array by values in the 2nd dimension. My code
prints sales data in order of the 1st dimension of the array, so all I
need to do is change the order of the dimension to change the output.
Here's my array:
$salesdata = array
(
array
(
"1", //store number
"1580", //sales
"1151", //plan sales
"1441", //ly sales
"508", //sgp
"561", //plan sgp
"621", //ly sgp
"38", //tix
"-10", //tix var
),
array
(
"2", //store number
"1493", //sales
"1520", //plan sales
"2040", //ly sales
"610", //sgp
"1106", //plan sgp
"483", //ly sgp
"62", //tix
"0", //tix var
),
array
(
"3", //store number
"1987", //sales
"989", //plan sales
"1030", //ly sales
"997", //sgp
"482", //plan sgp
"554", //ly sgp
"63", //tix
"13", //tix var
),
)
I want to be able to sort by any value, but I can work out that part.
Let's say I wanted to sort by sales, how would I do that?
Thanks!

Elegant way to update model

Elegant way to update model

Lets say I have a model with more then 20 properties.
Some of them can be edited in a view by the user, however for security
reasons data like passwords are not kept in hidden fields, so when I post
view model to controller some properties are nulls
How to check which properties changed without writing too much code?
bad idea:
[HttpPost]
public ActionResult Edit(BigModel model)
{
BigModel old=db.Get(new.id);
if(model.Property1 !=null && old.Property1 != model.Property1)
old.Property1=model.Property1
if(model.Property1 !=null && old.Property1 != model.Property1)
old.Property1=model.Property1
if(model.Property1 !=null && old.Property1 != model.Property1)
old.Property1=model.Property1
...
if(model.Property1 !=null && old.Property20 != model.Property20)
old.Property20=model.Property20
}

Ajax call not executed by button click in mvc4

Ajax call not executed by button click in mvc4

I am trying to refresh grid in partial view using AJAX call of button
click. But click method of button is not working properly.
Following code snippet is code i am using to execute
JQUERY
<script type="text/javascript">
$(document).ready(
function ()
{
$("#fromDate").datepicker({changeMonth: true, changeYear:
true });
$("#toDate").datepicker({changeMonth: true, changeYear:
true});
});
//function buttonClick() {
$("#btnSearch").click($.ajax({ url: 'Report/SearchGrid', type:
"POST", success: function (html) { } }));
//}
</script>
Razor Code
<input type="button" value="Search" id="btnSearch" onclick=
"buttonClick();" style="width: 90px; border: solid 1px #1570a6;
background-color: #1570a6; color: #FFFFFF; font-weight: 100;" />
Controller Code
public ActionResult SearchGrid(ExpenseReportModel model)
{
ExpenseReportModel expModel = new ExpenseReportModel();
expModel.ExpenseList = GetExpenseList();
expModel.ExpenseFromDate = Convert.ToDateTime(model.ExpenseFromDate);
expModel.ExpenseToDate = Convert.ToDateTime(model.ExpenseToDate);
return PartialView("_GridData", expModel.ExpenseList);
}

Conditionally compile if boost is present

Conditionally compile if boost is present

I want to conditionally compile some c++ code that uses boost, and make it
so it doesn't try to compile the boost dependent code if boost is not
present.
Does boost have any global macro that will be defined, like __BOOST__,
that I can check for?

Error in memory allocation for array of structures

Error in memory allocation for array of structures

[code]
struct box
{
char word[200][200];
char meaning[200][200];
int count;
};
struct root {
box *alphabets[26];
};
root *stem;
box *access;
void init(){
//cout<<"start";
for(int i = 0 ; i<= 25; i++){
struct box *temp =(struct box*)( malloc(sizeof(struct box)*100));
temp->count = 0;
cout<<temp->count;
stem->alphabets[i] = temp;
}
//cout<<" initialized";
}
[/code] It got compiled without errors.. But during itz execution it stops
at the point where 'temp' is allocated to 'stem->alphabets[i]'... How to
fix this.??

Jquery: elements value is not coming correct

Jquery: elements value is not coming correct

I trying to get the all input elements having name="choices" before
submit. And i want to check the values of those elements before submiting
the form . The problem is instead of getting the 0 ,1 ,2 which is values
of elements i'm getting undefined (3 times).
form
<form action="/check" method="post" id="mform1" >
<div id="id_poll_choices" >
A). <input type="text" id="id_ch" name="choices"
value="0"><br>
B). <input type="text" id="id_ch" name="choices"
value="1"><br>
C). <input type="text" id="id_ch" name="choices"
value="2"><br>
</div>
<input type="submit" id="id_submit" value="Submit"/>
</form>
jquery
$('#mform1').submit(function(){
$( "input[name*='choices']" ).each(function(index, elm){
alert(elm.val)
});
});
alert showing undefined.
what could be the issue here ?

Friday, 13 September 2013

program to calculate the numeric value of a name

program to calculate the numeric value of a name

i'm trying to do program to calculate the numeric value of a name
that what i wrote
letters = {'a':1 , 'b':2 , 'c':3 , 'd':4 , 'e':5 , 'f':6 , 'g':7 , 'h':8 ,
'i':9 , 'j':10 , 'k':11, 'l':12, 'm':13, 'n':14, 'o':15, 'p':16, 'q':17 ,
'r':18 , 's':19 , 't':20 , 'u':21 , 'v':22, 'w':23 , 'x':24 , 'y':25 ,
'z':26 } n = eval(input("Enter a name: "))
total = 0
for character in n:
total = total + letters
print("Numberic Value:", n, total)
and this what i got >>>>>>>>>>>>> NameError: name 'dell' is not defined

How to get the return code from a batch/shell script that launched from C++ code

How to get the return code from a batch/shell script that launched from
C++ code

We have a C++ program, sometimes this program need to execute a user
defined batch/shell/ant script. We are not able to control how this script
runs. Is there a way to get the return code from C++ program?
Something like: exec a script.sh > status.tmp ?
We need to support both Windows and Linux.
Any ideas?

jQuery UI removeClass() removes only one match

jQuery UI removeClass() removes only one match

Here's the issue. For some unknown reason, this jQuery UI function only
removes the highlight on the first item with class ".folder", and doesn't
remove it from the rest whenever a different one is clicked. I can't find
anything possibly wrong with the code, yet it doesn't work. The API
documentation states it should affect each element that matches the
pattern.
What gives?
function init_ui(){
// (some other functions omitted)
$('.folder').click(function(){
$('.folder').children().eq(0).removeClass('highlighted');
$(this).children().eq(0).addClass('highlighted');
$(init_ui);
});
}
$(init_ui);
Solution:
Simply remove .eq(0), as that means it will only match the first element
of them all.

should function be defined before it is used in python?

should function be defined before it is used in python?

should the functions be defined before it is used? but why the following
code works:
def main():
dog()
def dog():
print("This is a dog.")
if __name__ == '__main__':
main()
I mean the dog() is defined after it is called, how this works?

How do I write a scraper that logs into secure sites using WebGains as an example?

How do I write a scraper that logs into secure sites using WebGains as an
example?

I'm writing a scraper for WebGains to pick up commission details etc (they
don't provide an API).
I'm using PHP and cURL. I'm stuck right at the beginning for this scraper
- Once I'm logged into the website I'll be fine from there.
I used Fiddler to check any parameters being passed but since it uses SSL
this doesn't help.
I then used the Chrome Extension Virtual Event to view the event-driven
code under the login button which I discovered is all in the following
file:
http://us.webgains.com/public/wp-content/themes/clean-home/js/login.js
From that, I've gathered that I need to call the page
'https://us.webgains.com/loginform.html?action=checkauth&callback=?' to do
the login.
I'm trying to call that with my username and password (using curl) and
then re-use the curl session for subsequent page requests to pick up
commission details I need to automate.
This page looks like a .html page, but presumably in reality it's got some
server side code going on. If I try to load it directly in the browser
it's empty.
When I call the page using curl (PHP code below), I get no response too.
Am I calling the right page?
Is there a better tool to figure out what page to call/parameters to pass
in order to log into a secure site?
How do I log into WebGains using PHP/cURL?
Here's the PHP code I have:
$targeturl =
"https://us.webgains.com/loginform.html?action=checkauth&callback=?";
$ch = curl_init($targeturl);
$cookie = 'cookies.txt';
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"username=myusername&password=mypassword");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
$response = curl_exec($ch);
echo "<textarea cols=60 rows=10>" . print_r(curl_getinfo($ch), true) .
"</textarea>";
echo "<textarea cols=60 rows=10>" . curl_getinfo($ch,
CURLINFO_EFFECTIVE_URL) . "</textarea>";
echo "<textarea cols=60 rows=10>" . $response . "</textarea>";

Passing a C++ std::Vector to numpy array in Python

Passing a C++ std::Vector to numpy array in Python

I am trying a pass a vector of doubles that I generate in my C++ code to a
python numpy array. I am looking to do some downstream processing and want
to use some python facilities, once I populate the numpy array. Though I
am not very clear as to how to do it. I went though the Python C API
documentation and came across a function PyArray_SimpleNewFromData that
apparently can do the trick.
I am building certain very simple test cases to help me understand this
process. I generated the following code as a standlone Empty project in
Visual Studio express 2012. I call this file Project1
#include <Python.h>
#include
"C:/Python27/Lib/site-packages/numpy/core/include/numpy/arrayobject.h"
PyObject * testCreatArray()
{
float fArray[5] = {0,1,2,3,4};
npy_intp m = 5;
PyObject * c = PyArray_SimpleNewFromData(1,&m,PyArray_FLOAT,fArray);
return c;
}
My goal is to be able to read the PyObject in Python. I am stuck because I
don't know how to reference this module in Python. In particular how do I
import this Project from Python, I tried to do a import Project1, from the
project path in python, but failed.
Any experts who can help me with this, or maybe post a simple well
contained example of some code that reads in and populated a numpy array
from a c++ vector, I will be grateful. Many thanks in advance.

Thursday, 12 September 2013

How Perl can execute a command in the same shell with it?

How Perl can execute a command in the same shell with it?

I am not sure whether the title is really make sense to this problem. My
problem is simple, I want to write a perl script to change my current
directory and hope the result can be kept after calling the perl script.
The script looks like this:
if ($#ARGV != 0) {
print "usage: mycd <dir symbol>";
exit -1;
}
my $dn = shift @ARGV;
if ($dn eq "kite") {
my $cl = `cd ./private`;
print $cl."\n";
}
else {
print "unknown directory symbol";
exit -1;
}
However, my current directory doesn't change after calling the script.
What is the reason? How can I resolve it?

Is Xcode5 stable?

Is Xcode5 stable?

I couldn't readily identify if Xcode 5 is stable release/out of beta, and
it's getting about that time no? There's also no indication if Xcode5 is
stable release or beta on developer.apple.com
I think it was recently announced iOS7 is officially released in 6 days
(Sep 18). It wouldn't surprise me if Xcode5 is official now.

How to change axis limits for time in Matplotlib?

How to change axis limits for time in Matplotlib?

I have a data set stored in a Pandas dataframe object, and the first
column of the dataframe is a datetime type, which looks like this:
0 2013-09-09 10:35:42.640000
1 2013-09-09 10:35:42.660000
2 2013-09-09 10:35:42.680000
3 2013-09-09 10:35:42.700000
In another column, I have another column called eventno, and that one
looks like:
0 0
1 0
2 0
3 0
I am trying to create a scatter plot with Matplotlib, and once I have the
scatter plot ready, I would like to change the range in the date axis
(x-axis) to focus on certain times in the data. My problem is, I could not
find a way to change the range the data will be plotted over in the x
axis. I tried this below, but I get a Not implemented for this type error.
plt.figure(figsize=(13,7), dpi=200)
ax.set_xlim(['2013-09-09 10:35:00','2013-09-09 10:36:00'])
scatter(df2['datetime'][df.eventno<11],df2['eventno'][df.eventno<11])
If I comment out the ax.set.xlim line, I get the scatter plot, however
with some default x axis range, not even matching my dates.
Do I have to tell matplotlib that my data is of datetime type, as well? If
so, then how can I do it? Assuming this part is somehow accomplished, then
how can I change the range of my data to be plotted?
Thanks!
PS: I tried uploading the picture, but I got a "Framing not allowed"
error. Oh well... It just plots it from Jan 22 1970 to Jan 27 1970. No
clue how it comes up with that :)

How do you read input into a variable?

How do you read input into a variable?

I am a beginner with using Python. I am writing a simple program to would
calculate the radius of a circle.
input math
I = input
p = "3.14"
n = "6.28"
I/n
When I run this I get an "integrated function" error because I use
input(). Is there any way I can put the input() data to a variable?
At first I thought that there was a simple syntax error behind all of
this, but after I tried out every single thing that I could, I have given
up all hope on it.

How do I create separate config files for different configurations?

How do I create separate config files for different configurations?

I have multiple configurations and so I need different App.config files
for the different environments/configurations. Question is how do I
generate these separate files? I remember I used to be able to right click
on the file and click on something to do it but I don't see anything to do
that right now.

Rails - how to make Geocoder "near" query with "where" condition?

Rails - how to make Geocoder "near" query with "where" condition?

I am working with the Geocoder gem and there is mentioned this snippet for
searching records within a distance:
Venue.near('Omaha, NE, US', 20)
This is working well, but I would need to add another condition. This is
the query I currently use:
Car.where('car.status = ? AND listings.sold IS ?', 1,
nil).includes(:images, :user)
And to this query I am trying to add the near call, like this:
Car.near('90013', 20).('car.status = ? AND listings.sold IS ?', 1,
nil).includes(:images, :user)
But result of this query is just nil.
What is the correct way to combine near query with where condition?

cocoa: detect inactive states of all the running application

cocoa: detect inactive states of all the running application

Greetings! I am very new to this cocoa and I am trying to achieve
something like activity monitor. i have list of all the running
applications and I would like to observe these app and get notified when
any app goes to [Not Responding] state like in activity monitor. Checked
NSWorkSpace and NSRunningApplication but didnt got much help.
Please enlighten me on this.
Thanks in advance Ankit

Wednesday, 11 September 2013

how do javascript objects constructed with both dot and literal notation behave when called?

how do javascript objects constructed with both dot and literal notation
behave when called?

While running the code below, without any function calls, I would
immediately get this output
["1122","3rd St","Seattle","WA","92838"]
The closest thread that addressed this code was Need Explanation:
Organization with Objects in a Contact List (Javascript, Codecademy) but
it didn't quite address my concern.
I'm sure that the way I had added key,value pairs to the objects is
somehow yielding this output, but I can't seem to explain why, especially
when running the code, there is no function call included.
When actually trying to call search (e.g. search("steve")), it would fail
but it would work on search("bill"). I thought it might be related to the
javascript console but I checked using Chrome's console with the same
results. Any help would be much appreciated.
var friends={};
friends.bill = {};
friends.steve={};
friends.bill["firstName"]="Bill";
friends.bill["lastName"]="Gates";
friends.bill.number="333.222.3937";
friends.steve["firstName"]="Steve";
friends.steve.lastName="Ballmer";
friends.steve["number"]="829.383.3939";
friends.bill["number"]="232.8392.2382"
friends.bill.address=['5353','Cook Ave','Bellevue','CA','94838']
friends.steve.address=['1122','3rd St','Seattle','WA','92838']
var search=function(name)
{
for(var i in friends){
if (name==i["firstName"])
{
console.log(friends[i])
return friends[i]
}
else{
return "no match"
}
}
}

Does the actual value of a enum class enumeration remain constant/invariant?

Does the actual value of a enum class enumeration remain constant/invariant?

Given code for an incomplete server like:
enum class Command : uint32_t {
LOGIN,
MESSAGE,
JOIN_CHANNEL,
PART_CHANNEL,
INVALID
};
Can I expect that converting Command::LOGIN to an integer will always give
the same value?
Across compilers?
Across compiler versions?
If I add another enumeration?
If I remove an enumeration?
Converting Command::LOGIN would look something like this:
uint32_t number = static_cast<uint32_t>(Command::LOGIN);
Some extra information on what I am doing here. This enumeration is fed
onto the wire by converting it to an integer sending it along to the
server/client. I do not really particularly care what the number is, as
long as it will always stay the same. If it will not stay the same, then
obviously I will have to provide my own numbers through the usual way.
Now my sneaking suspicion is that it will change depending on what
compiler was used to compile the code, but I would like to know for sure.
Bonus question: How does the compiler/language determine what number to
use for Command::LOGIN?
Before submitting this question, I have noticed some changes from say
3137527848 to 0 and back, so it is obviously not valid to rely on it not
changing. I am still curious about how this number is determined, and how
or why that number is changing.

block double request while ajax is pending

block double request while ajax is pending

i really need to understand how block the requests ajax while is pending.
Let me exaplain a example:
I have a input type called "share" and when i write something and press
enter ajax take the result and it insert inside mysql. If i do this
pressing a lot of time the enter button it take more results like how many
times i pressed enter even if there is a control in php. I think is a
problem of the request ajax because the control php I'm sure is right.
Thank you so much.
this is the code of example:
form
<input type="text" class="share">
Js
$.fn.enterKey = function (fnc) { // function for check when i press enter
return this.each(function () {
$(this).keypress(function (ev) {
var keycode = (ev.keyCode ? ev.keyCode : ev.which);
if (keycode == '13') {
fnc.call(this, ev);
}
})
})
}
$('.share').enterKey(function() { // ajax request
var comment = $(this);
if (comment.val() != "") {
$.ajax({
type: "POST",
url: add_comment.urlRemove,
data: "text=" + comment.val(),
success: function(html) {
comment.val('');
},
error: function(){
alert('Error on ajax call');
}
});
} else {
return false;
}
});
}

Rails 4: Flash messages linger for an extra page view

Rails 4: Flash messages linger for an extra page view

I am using the following code in my layout to display two types of flash
messages:
<% if !flash[:notice].nil? %>
<div class="row">
<div class="flash notice col-xs-12">
<%= flash[:notice] %>
</div>
</div>
<% end %>
<% if !flash[:error].nil? %>
<div class="row">
<div class="flash error col-xs-12">
<%= flash[:error] %>
</div>
</div>
<% end %>
<%= debug(flash[:notice]) %>
<%= debug(flash[:error]) %>
They both work fine, but whenever one is triggered, it will still appear
for one additional page view. I'm not using any caching gems.
Why is this happening? And how do I fix it?

Is it a good practice to create a sidebar using Javascript?

Is it a good practice to create a sidebar using Javascript?

A couple of months ago I realized I needed to update a sidebar annually
with a new link. Now instead of going through each page and inserting the
link (about 20 pages), I decided to create a javascript file and link it
to each page. The script would create links and append them to the page.
This meant that each time we needed to create a new link, we'd only need
to add a new line to the javascript file once and the change would be
reflected on each page. Essentially cutting down on time wasted going
through all pages and adding the new link. I wonder if this is a good
practice and could there be problems I failed to foresee?
The code is listed below:
function createVolume (text, link){
var volDiv = document.createElement("div");
var textDiv = document.createTextNode(text);
var linkDiv = document.createElement("a");
linkDiv.setAttribute("href", link);
volDiv.setAttribute("class", "volume");
volDiv.appendChild(textDiv);
linkDiv.appendChild(volDiv);
var d = document.getElementById("e27");
d.appendChild(linkDiv);
}
var bhbHome = createVolume("BHB Home", "bhb.html");
var v76 = createVolume("Volume 76", "bhb76.html");
var v75 = createVolume("Volume 75", "bhb75.html");
var v74 = createVolume("Volume 74", "bhb74.html");
var v73 = createVolume("Volume 73", "bhb73.html");
var v72 = createVolume("Volume 72", "bhb72.html");
var v71 = createVolume("Volume 71", "bhb71.html");
var v70 = createVolume("Volume 70", "bhb70.html");
var v69 = createVolume("Volume 69", "bhb69.html");
var v68 = createVolume("Volume 68", "bhb68.html");
var v67 = createVolume("Volume 67", "bhb67.html");
var v6566 = createVolume("Volume 65 and 66", "bhb_65_66.html");
var v64 = createVolume("Volume 64", "bhb64.html");
var v63 = createVolume("Volume 63", "bhb63.html");
var v626160 = createVolume("Volume 60, 61, and 62", "bhb_60_61_62.html");
var v59 = createVolume("Volume 59","bhb59.html");

scrollTop doesn´t work on site change

scrollTop doesn´t work on site change

On my site I have the Problem that when I´m coming from the Imprint or
How-to-find-us Site and I click on service or contact, the scrollTop
doesn´t work correktly.
http://wicker-schuetz.de/en/
thanks

Trouble: QWebView with local html which includes local javascript

Trouble: QWebView with local html which includes local javascript

I am developing an application wich loads a local html inside a QWebView
in this way:
ui->webView->setUrl(QUrl("qrc:/index.html"));
and the page is correctly loaded but not the javascript. Here the html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="utils.js"></script>
</head>
<body>
<input type="button" value="test" onclick="test_func();"/>
</body>
</html>
so, in utils.js I have test_func() but it does not work.
Any idea? Thanks.

Tuesday, 10 September 2013

Jquery mobile, working with multiple pages

Jquery mobile, working with multiple pages

suppose I've following html along with jquery mobile linked:
<section id="firstpage" data-role="page">
<label for="a">Enter a</label>
<input id="a" type="number"/>
<label for="b">Enter b</label>
<input id="b" type="number"/>
<label for="c">Enter c</label>
<input id="c" type="number"/>
<a href="#secondpage" data-role="button" data-transition="flip">Show
Them!</a>
</section>
<section id="secondpage" data-role="page">
<!--I want to show the three values of a,b,c here -->
</section>
As you can see the first page will have a button, and when I'll press that
it'll direct me to the second page. Now, suppose I'm saving the input
field values to three variables in my script. How to show them in the
second page, I'm getting stucked at that?
If you just write a simple jquery script that will take these three values
in the first page and show them when directed in the second page in its
inner html, that'll work for me.

Forming a parent child structure using the data from the result set

Forming a parent child structure using the data from the result set

I am developing a webpage where the user can able to select the list of
options based on the category.So a parent node has the category and the
child node has the list of options to select using a radio button.
here it goes
After Retrieving the records from the database
while(resultSet.next())
{
entertainment = resultSet.getString(1);
listofChoices = resultSet.getString(2);
}
In this looping , i need to form a parent child structure and store it in
a map(Key value pair combination) to pass it to my JSP page.
1.Not all child nodes come under the category.This means that the list of
choices can be congifured under null category also.
Is there any way on how to achieve this?
Ex:
Entertainment Themeparks
Entertainment Casino
NULL ToyStore
Thanks for your help ...

How to check if an element with id exists or not in jQuery?

How to check if an element with id exists or not in jQuery?

I'm generating a div dynamically and I've to check whether a dynamically
generated div exists or not ? How can I do that?
Currently I'm using the following which does not detects the div generated
dynamically. It only detects if there is already an element with the id
contained in the HTML template.
$(function() {
var $mydiv = $("#liveGraph_id");
if ($mydiv.length){
alert("HHH");
}
});
How can I detect the dynamically generated div?

How to sort messages?

How to sort messages?

I'm a novice programmer in PHP.
I have a simple messaging site with users in one table and another table
with messages:
(date, from user, to users, message, primary key, subject).
First of all, I'm not sure this is the right way to have messages stored,
so please tell me.
What I'm confused about is the display of the messages.
I want the page script to:
connect to the database
authenticate user
go through all messages in messages table (good up to here)
go through the to users field, see if user is one of them (splits it up
into array)
if it is:
check to see if any other messages have the same users in their to users
field
if it is:
group it with the others with the same users in their to users field
(possibly in a second dimension of a multidimensional array)
else:
put it into a new "group" (with the next first dimension of a
multidimensional array)
Then, I'll display only the ones of the first dimension of the
multidimensional array, and when clicked will display the rest of the
messages (all the second dimensions of a multidimensional array) in
another place.
If somebody could help me with these steps with some bits of code or links
to a website that could help, please do so.
Please help! I really have no clue how to do this - I've tried a few times
but it's taken so much time and effort, I think I'll need some help.
Thanks in advance.

What is the difference between these ways of getting current directory?

What is the difference between these ways of getting current directory?

They all give the same result, the location of folder that contains the
exe that is being executed. I am sure there are no good or bad methods in
the .net BCL. They are all appropriate in particular circumstances. Which
one is appropriate for which scenario?
var appBaseDir = AppDomain.CurrentDomain.BaseDirectory;
var currentDir = Environment.CurrentDirectory;
var dir = Directory.GetCurrentDirectory();
var path =
Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

MYSQL and operator

MYSQL and operator

SELECT
Registration.R_no,
Registration.P_name,
Registration.Registerno,
DailyEntry.Tokenno,
DailyEntry.ArrivalTime,
DailyEntry.ConsultationTime,
DailyEntry.DispencngTime,
DailyEntry.token,
DailyEntry.prior,
DailyEntry.priorvip,
DailyEntry.delete_token
FROM
Registration,
DailyEntry
WHERE Registration.R_no = DailyEntry.R_no
AND Registration.R1_date = '2013-09-10'
ORDER BY DailyEntry.Tokenno
This sql command is returning an empty row. But data is there in the
table. Anybody please tell what is the problem

Passing a jQuery load() function variable to codeigniter controller

Passing a jQuery load() function variable to codeigniter controller

is there a way to pass a variable to a codeigniter controller using
jquery's load() function?
currently this is my non working code
main.php
<input type="hidden" id="url" name="url" value="<?php echo
base_url();?>site/pax_dropdown/" />
<input type="hidden" val="2" id="value">
<ul id="result" class="dropdown-menu">
<?php $this->load->view("site/pax_dropdown"); ?>
</ul>
pax_dropdown.php
<li><a href="">3</a></li>
<li><a href="">4</a></li>
<li><a href="">5</a></li>
<li><a href="">6</a></li>
<li><a href="">7</a></li>
<li><a href="">8</a></li>
<li><a href="">9</a></li>
<?php
echo $id;
?>
script.js
var url = $("#url").val();
var val = $("#value").val();
$('#result').load(url,val);
controller
public function pax_dropdown($id)
{
$data['id'] = $id;
$this->load->vars($data);
$this->load->view("site/pax_dropdown");
}
with this code the pax_dropdown.php successfully loads inside the
<ul id="result">
in my main.php however my test variable $id cannot be found and says
Message: Undefined variable: id am i doing something wrong?



by the way i also tried sending the variable to the controller this way:
main
<input type="hidden" id="url" name="url" value="<?php echo
base_url();?>site/pax_dropdown/2" />
i placed the variable to be passed at the end of the url, which in this
case is "2"
and it still did not work

How do i compute the sum n+n/2+n/3+n/4........+(n/n) in less than O(n) time?

How do i compute the sum n+n/2+n/3+n/4........+(n/n) in less than O(n) time?

I need an algorithm that has time complexity less than O(n).
Currently I have this algorithm:
int n; sum=n; for(int i=2;i<=n;i++) { sum+=n/i; }

Monday, 9 September 2013

Facebook friends pictures for External urls

Facebook friends pictures for External urls

I want to display facebook friends pictures who have liked a external url.
Let me know if there is any way?. I have tried with all the social
plugins.

service not starting on windows vista error 1053

service not starting on windows vista error 1053

I've got a service running on windows 7, but when i move it to windows xp.
It gives following message when starting it:
"Could not start the service on local computer. Error 1053: The Service
did not respond to start or control request in timely fashion."
Please help me out.
Following is my service code:
int _tmain (int argc, TCHAR *argv[])
{
OutputDebugString(_T("My Sample Service: Main: Entry"));
SERVICE_TABLE_ENTRY ServiceTable[] =
{
{SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION) ServiceMain},
{NULL, NULL}
};
if (StartServiceCtrlDispatcher (ServiceTable) == FALSE)
{
OutputDebugString(_T("My Sample Service: Main:
StartServiceCtrlDispatcher returned error"));
return GetLastError ();
}
OutputDebugString(_T("My Sample Service: Main: Exit"));
return 0;
}
VOID WINAPI ServiceMain (DWORD argc, LPTSTR *argv)
{
DWORD Status = E_FAIL;
OutputDebugString(_T("My Sample Service: ServiceMain: Entry"));
g_StatusHandle = RegisterServiceCtrlHandler (SERVICE_NAME,
ServiceCtrlHandler);
if (g_StatusHandle == NULL)
{
OutputDebugString(_T("My Sample Service: ServiceMain:
RegisterServiceCtrlHandler returned error"));
goto EXIT;
}
// Tell the service controller we are starting
ZeroMemory (&g_ServiceStatus, sizeof (g_ServiceStatus));
g_ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
g_ServiceStatus.dwControlsAccepted = 0;
g_ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
g_ServiceStatus.dwWin32ExitCode = 0;
g_ServiceStatus.dwServiceSpecificExitCode = 0;
g_ServiceStatus.dwCheckPoint = 0;
if (SetServiceStatus (g_StatusHandle, &g_ServiceStatus) == FALSE)
{
OutputDebugString(_T("My Sample Service: ServiceMain: SetServiceStatus
returned error"));
}
/*
* Perform tasks neccesary to start the service here
*/
OutputDebugString(_T("My Sample Service: ServiceMain: Performing Service
Start Operations"));
// Create stop event to wait on later.
g_ServiceStopEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
if (g_ServiceStopEvent == NULL)
{
OutputDebugString(_T("My Sample Service: ServiceMain:
CreateEvent(g_ServiceStopEvent) returned error"));
g_ServiceStatus.dwControlsAccepted = 0;
g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
g_ServiceStatus.dwWin32ExitCode = GetLastError();
g_ServiceStatus.dwCheckPoint = 1;
if (SetServiceStatus (g_StatusHandle, &g_ServiceStatus) == FALSE)
{
OutputDebugString(_T("My Sample Service: ServiceMain:
SetServiceStatus returned error"));
}
goto EXIT;
}
// Tell the service controller we are started
g_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
g_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
g_ServiceStatus.dwWin32ExitCode = 0;
g_ServiceStatus.dwCheckPoint = 0;
if (SetServiceStatus (g_StatusHandle, &g_ServiceStatus) == FALSE)
{
OutputDebugString(_T("My Sample Service: ServiceMain: SetServiceStatus
returned error"));
}
// Start the thread that will perform the main task of the service
hThread = CreateThread (NULL, 0, ServiceWorkerThread, NULL, 0, NULL);
OutputDebugString(_T("My Sample Service: ServiceMain: Waiting for Worker
Thread to complete"));
// Wait until our worker thread exits effectively signaling that the
service needs to stop
WaitForSingleObject (hThread, INFINITE);
OutputDebugString(_T("My Sample Service: ServiceMain: Worker Thread Stop
Event signaled"));
/*
* Perform any cleanup tasks
*/
OutputDebugString(_T("My Sample Service: ServiceMain: Performing Cleanup
Operations"));
CloseHandle (g_ServiceStopEvent);
g_ServiceStatus.dwControlsAccepted = 0;
g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
g_ServiceStatus.dwWin32ExitCode = 0;
g_ServiceStatus.dwCheckPoint = 3;
if (SetServiceStatus (g_StatusHandle, &g_ServiceStatus) == FALSE)
{
OutputDebugString(_T("My Sample Service: ServiceMain: SetServiceStatus
returned error"));
}
EXIT:
OutputDebugString(_T("My Sample Service: ServiceMain: Exit"));
return;
}
VOID WINAPI ServiceCtrlHandler (DWORD CtrlCode)
{
OutputDebugString(_T("My Sample Service: ServiceCtrlHandler: Entry"));
switch (CtrlCode)
{
case SERVICE_CONTROL_STOP :
OutputDebugString(_T("My Sample Service: ServiceCtrlHandler:
SERVICE_CONTROL_STOP Request"));
if (g_ServiceStatus.dwCurrentState != SERVICE_RUNNING)
break;
/*
* Perform tasks neccesary to stop the service here
*/
g_ServiceStatus.dwControlsAccepted = 0;
g_ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
g_ServiceStatus.dwWin32ExitCode = 0;
g_ServiceStatus.dwCheckPoint = 4;
if (SetServiceStatus (g_StatusHandle, &g_ServiceStatus) == FALSE)
{
OutputDebugString(_T("My Sample Service: ServiceCtrlHandler:
SetServiceStatus returned error"));
}
// This will signal the worker thread to start shutting down
SetEvent (g_ServiceStopEvent);
//OutputDebugString(_T("My Sample Service: ServiceMain: Killing
thread"));
//CloseHandle(hThread);
break;
default:
break;
}
OutputDebugString(_T("My Sample Service: ServiceCtrlHandler: Exit"));
}
DWORD WINAPI ServiceWorkerThread (LPVOID lpParam)
{
OutputDebugString(_T("My Sample Service: ServiceWorkerThread: Entry"));
// Periodically check if the service has been requested to stop
while (WaitForSingleObject(g_ServiceStopEvent, 0) != WAIT_OBJECT_0)
{
/*
* Perform main service function here
*/
}
OutputDebugString(_T("My Sample Service: ServiceWorkerThread: Exit"));
return ERROR_SUCCESS;
}
Thanks, KM.

How to submit a form upon selection of an option?

How to submit a form upon selection of an option?

Is there a simple way to use a drop down select menu as a submit button as
well? I'd prefer to not have an <input type="submit" name="submit">, just
for the form to auto-submit upon selection of an option? Javascript,
jquery, php, css and pure HTML answers all work for me.
<form name="order" action="" method="get">
<select type="submit" name="carlist">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</form>

sorting a datagrid with GWT

sorting a datagrid with GWT

I have a datagrid in GWT, and I'm using RPC to populate it with data, I
can get the data to show up just fine, and I can also select individual
cells but when it comes to sorting it just doesn't work! I can occasionaly
click on column headers (it happens intermittently and I'm not sure why)
but when I do nothing sorts. I'm using a dataProvider, but I think I'm
implementing it incorrectly, I've attached the related code, can someone
give me a pointer on how to do this correctly?
first is the actual table itself
public class GuiInventory {
public final static LayoutPanel hpMain = new LayoutPanel();
static ListHandler<OpInventory> sortHandler;
/*
* Define a key provider for a Contact. We use the unique ID as the key,
* which allows to maintain selection even if the name changes.
*/
static ProvidesKey<OpInventory> keyProvider = new
ProvidesKey<OpInventory>() {
@Override
public Object getKey(OpInventory item) {
// Always do a null check.
return (item == null) ? null : item.getPartID();
}
};
//the table
final static DataGrid<OpInventory> table = new
DataGrid<OpInventory>(keyProvider);
final static SelectionModel<OpInventory> selectionModel = new
MultiSelectionModel<OpInventory>(keyProvider);
/**
* The provider that holds the list of contacts in the database.
*/
private final static ListDataProvider<OpInventory> dataProvider = new
ListDataProvider<OpInventory>();
public ListDataProvider<OpInventory> getDataProvider() {
return dataProvider;
}
/**
* Add a display to the database. The current range of interest of the
display
* will be populated with data.
*
* @param display a {@Link HasData}.
*/
public void addDataDisplay(HasData<OpInventory> display) {
dataProvider.addDataDisplay(display);
}
/**
* Refresh all displays.
*/
public void refreshDisplays() {
dataProvider.refresh();
}
public static Widget init() {
hpMain.clear();
table.setWidth("100%");
table.setSelectionModel(selectionModel);
Ioma.dataservice.getPartInventory(new
AsyncCallback<ArrayList<OpInventory>>() {
@Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
}
@Override
public void onSuccess(ArrayList<OpInventory> result) {
dataProvider.setList(result);
// Attach a column sort handler to the ListDataProvider to
sort the list.
sortHandler = new ListHandler<OpInventory>(result);
table.addColumnSortHandler(sortHandler);
dataProvider.addDataDisplay(table);
if (table.getColumnCount() == 0) {
initTable();
}
}
});
//add in table
hpMain.add(table);
return hpMain;
}
public static void initTable() {
// Add a text column to show the part ID.
Column<OpInventory, Number> partIDColumn = new Column<OpInventory,
Number>(new NumberCell()) {
@Override
public Integer getValue(OpInventory object) {
return object.getPartID();
}
};
table.addColumn(partIDColumn, "Part ID");
table.setColumnWidth(partIDColumn, 4, Unit.PX);
//add a sort to partID
partIDColumn.setSortable(true);
sortHandler.setComparator(partIDColumn, new Comparator<OpInventory>() {
@Override
public int compare(OpInventory o1, OpInventory o2) {
return Integer.valueOf(o1.getPartID()).compareTo(o2.getPartID());
}
});
// Add a text column to show the part Number.
Column<OpInventory, String> partNumberColumn = new Column<OpInventory,
String>(new EditTextCell()) {
@Override
public String getValue(OpInventory object) {
return object.getPartNumber();
}
};
table.addColumn(partNumberColumn, "Part Number");
table.setColumnWidth(partNumberColumn, 4, Unit.PX);
//add a sort to the part Number
partNumberColumn.setSortable(true);
sortHandler.setComparator(partNumberColumn, new
Comparator<OpInventory>() {
@Override
public int compare(OpInventory o1, OpInventory o2) {
return o1.getPartNumber().compareTo(o2.getPartNumber());
}
});
//add a field updater to be notified when the user enters a new Part
Number
partNumberColumn.setFieldUpdater(new FieldUpdater<OpInventory,
String>() {
@Override
public void update(int index, OpInventory object, String value) {
object.setPartNumber(value);
//TODO add async call to database to update part Number
table.redraw();
}
});
// Add a text column to show the name.
Column<OpInventory, String> nameColumn = new Column<OpInventory,
String>(new EditTextCell()) {
@Override
public String getValue(OpInventory object) {
return object.getName();
}
};
table.addColumn(nameColumn, "Name");
table.setColumnWidth(nameColumn, 10, Unit.PX);
//add a field updater to be notified when the user enters a new part name
nameColumn.setFieldUpdater(new FieldUpdater<OpInventory, String>() {
@Override
public void update(int index, OpInventory object, String value) {
object.setName(value);
//TODO add async call to database to update part name
table.redraw();
}
});
//add a sort to the name
nameColumn.setSortable(true);
sortHandler.setComparator(nameColumn, new Comparator<OpInventory>() {
@Override
public int compare(OpInventory o1, OpInventory o2) {
return o1.getName().compareTo(o2.getName());
}
});
}
this is the Opinventory class to hold each object in the datagrid
public class OpInventory implements Comparable<OpInventory>, IsSerializable {
int partID;
String partNumber;
String name;
String desc;
String partLotNumber;
String supplier;
String reOrderNumber;
boolean isActive;
int quantity;
Double price;
/**
* The key provider that provides the unique ID of a contact.
*/
public static final ProvidesKey<OpInventory> KEY_PROVIDER = new
ProvidesKey<OpInventory>() {
@Override
public Object getKey(OpInventory item) {
return item == null ? null : item.getPartID();
}
};
@Override
public int compareTo(OpInventory o) {
return (o == null || o.partNumber == null) ? -1 :
-o.partNumber.compareTo(partNumber);
}
@Override
public boolean equals(Object o) {
if (o instanceof OpInventory) {
return partID == ((OpInventory) o).partID;
}
return false;
}
@Override
public int hashCode() {
return partID;
}
public OpInventory(int partID, String partNumber, String name, String
desc, String partLotNumber, String supplier, String reOrderNumber, Double
price, boolean isActive) {
this.partID = partID;
this.partNumber = partNumber;
this.name = name;
this.desc = desc;
this.partLotNumber = partLotNumber;
this.supplier = supplier;
this.reOrderNumber = reOrderNumber;
this.price = price;
this.isActive = isActive;
}
public OpInventory() {
}
//getters and setters here
}