Monday, 30 September 2013

Disable automatic connect in Infrastructure mode?

Disable automatic connect in Infrastructure mode?

I installed pfsense on a new system with an atheros based wlan card. I
configured this card as WAN, it was automatically put into infrastructure
mode which has one problem: it simply connects to the next SSID it finds!
I do not want any automatic connect from my pfsense system to some random
WLAN!
Quote from the GUI about the SSID field of my WAN interface (=WLAN card):
Note: Only required in Access Point mode. If left blank in Ad-hoc
or Infrastructure mode, this interface will connect to any available SSID
Is it possible to disable this behaviour before even configuring my WLAN
card as WAN, so that - on my next attempt to install a new system -
pfsense will never ever connect randomly to a WLAN!? Using the intial,
console based interface configuration, is it possible to configure my WLAN
card as WAN but letting the interface disabled until I configured it
properly?

Installing mcrypt extension on CentOS 6

Installing mcrypt extension on CentOS 6

I am trying to install the mcrypt extension on my CentOS 6 VPS. I have
done the EPEL rpm and then updated everything. Now, I keep getting this
error and I've also installed php-api.
[root@vps ~]# yum -y install php-mcrypt
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirror.raystedman.net
* epel: mirror.oss.ou.edu
* extras: mirror.teklinks.com
* updates: bay.uchicago.edu
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package php-mcrypt.x86_64 0:5.1.6-5.el5 will be installed
--> Processing Dependency: php-api = 20041225 for package:
php-mcrypt-5.1.6-5.el5.x86_64
--> Finished Dependency Resolution
Error: Package: php-mcrypt-5.1.6-5.el5.x86_64 (epel)
Requires: php-api = 20041225
Installed: php-common-5.3.3-23.el6_4.x86_64 (@updates)
php-api = 20090626
Available: php-common-5.3.3-22.el6.x86_64 (base)
php-api = 20090626
You could try using --skip-broken to work around the problem
You could try running: rpm -Va --nofiles --nodigest
AmI skipping/missing something important? Please don't down vote this.
Thank you!

properly setting the percentage height of a parent div and children divs

properly setting the percentage height of a parent div and children divs

I'm trying to figure this out without making to much of a mess here. I
have one container div then within it i have 3 more divs for wich are
floated left. My problem is that my container div has a style of height of
100%. like this
.Container {
height: 100%;
min-width: 600px;
overflow-y: hidden;
}
and the one of my child div inside the container div(sidebar1), (for the
sake of clarity ill keep it to just one div) has this css.
border: 1px solid #E0E0DF;
bottom: 10px;
box-shadow: 2px 2px 4px #888888;
float: left;
height: 100%;
overflow-y: scroll;
width: 18%;
}
I add "list" elements to the sidedar1 div using jquery.The problem that
I'm encountering is that i don't actually get the scroll bar to appear
until there are like 3 or 4 items past the view and even when the scroll
bar show up I can't scroll all the way down to see them. I understand it
has something to so with the parent being 100% height and the child also
being 100%. I cant see the bottom of the sidebar1 scroll plus i have the
scroll bar hidden for container div. what is the best way to do this? i
want to have container div that basically expand the full length and width
of the users screen without any scroll bars and then within it i would
like to have my child divs floated left but i don't want them to lose view
if that makes any sense. I would like to be able to see their full scroll
bar when they appear. Thanks in advance Miguel

How to save and display image into database without using move uploaded or copy functions in php

How to save and display image into database without using move uploaded or
copy functions in php

How to save and display image into database without using move uploaded or
copy functions in php ? Is it possible to do that without saving the
images into directories and saving them to database with some datatype for
that particular field ?

Sunday, 29 September 2013

App Rejected due to Data Storage

App Rejected due to Data Storage

I have an app that pre-loads data from a sqlite file and stores it with
core data. Apple rejected the app because the data is being backed up by
icloud.
How do I change core data to store it in another location or tell icloud
not to back up the data (or whatever else needs to be done to get the app
approved).

openGL limited 3D space

openGL limited 3D space

I'm having problem with my drawing code..I have to display some arrows,
but when they are too far from the origin of the axis they disappear..
Here I post my relevant code:
static void drawArrow( double trans[3][4] , double **d, int num, double
*altitude)
{
int i;
double c_min=0.3;
double gl_para[16];
GLfloat mat_ambient[] = {0.0, 0.0, 1.0, 1.0};
GLfloat mat_flash[] = {0.0, 0.0, 1.0, 1.0};
GLfloat mat_flash_shiny[] = {50.0};
GLfloat light_position[] = {100.0,-200.0,200.0,0.0};
GLfloat ambi[] = {0.1, 0.1, 0.1, 0.1};
GLfloat lightZeroColor[] = {0.9, 0.9, 0.9, 0.1};
argDrawMode3D();
argDraw3dCamera( 0, 0 );
glClearDepth( 1.0 );
glClear(GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
argConvGlpara(trans, gl_para);
glMatrixMode(GL_PROJECTION);
glLoadMatrixd( gl_para );
glRotated(-90,0,1,0);
glRotated(az-90,0,0,1);
for (i=0;i<num;i++)
{
if (altitude[i]>=quota && altitude[i]<quota+STEP_ALTITUDE){
if ( mode == 1 )
glColor3d((mod[1]-d[i][3])/(mod[1]-mod[0]),(d[i][3]-mod[0])/(mod[1]-mod[0]),0);
else
glColor3f((c_min*(d[i][3]-mod[0])+(mod[1]-d[i][3]))/(mod[1]-mod[0]),0,0);
glTranslated(d[i][0],d[i][1],d[i][2]);
glRotated(-d[i][5],0,0,1);
glRotated(d[i][4],1,0,0);
glRotated(-90,1,0,0);
glTranslated(0,0,d[i][3]*arrow_factor*(1-cone_para1));
glutSolidCone(d[i][3]*arrow_factor*cone_para1*cone_para2,
d[i][3]*arrow_factor*cone_para1,10,10);
glBegin(GL_LINES);
glVertex3d(0,0,0);
glVertex3d(0,0,-d[i][3]*arrow_factor*(1-cone_para1));
glEnd();
glTranslated(0,0,-d[i][3]*arrow_factor*(1-cone_para1));
glRotated(90,1,0,0);
glRotated(-d[i][4],1,0,0);
glRotated(d[i][5],0,0,1);
glTranslated(-d[i][0],-d[i][1],-d[i][2]);}
}
glDisable( GL_LIGHTING );
glDisable( GL_DEPTH_TEST );
}
I suppose I have to use GL_PROJECTION matrix mode, but I belive that if
there is a better way to let it work without change it at all..

How to read clob data and return string using TCL

How to read clob data and return string using TCL

How to read a clob data using tcl?
My function should read clob data and return a string in xml format.
Note: Table has 2 fields (Id, Image(clob))
Can any one help to resolve this prob?
I tried many option but got error like:
500 Status line too long (limit is 8192) at
/usr/lib/perl5/wayport/wprpc.pm line 125
and
nsoracle.c:2170:OracleLobSelect: error in `OCIStmtExecute ()': ORA-03135:
connection lost contact
Process ID: 11519
Session ID: 878 Serial number: 31261

How to fill a datatable with List

How to fill a datatable with List

How can convert a list to a datatable
[Serializable]
public class Item
{
public string Name { get; set; }
public double Price { get; set; }
public string @URL { get; set; }
public Item(string Name, string Price, string @URL)
{
this.Name = Name;
this.Price = Convert.ToDouble(Price);
this.@URL = @URL;
}
public override string ToString()
{
return this.Name;
}
}
I tried using:
static DataTable ConvertToDatatable(List<Item> list)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Price");
dt.Columns.Add("URL");
foreach (var item in list)
{
dt.Rows.Add(item.Name, Convert.ToString(item.Price), item.URL);
}
return dt;
}
and then tried to add the itemList to the itemTable:
List<Item> itemList = ...
itemTable = ConvertToDatatable(itemList);
itemDataView.DataSource = itemTable;
but i get itemDataView is null
Can anyone help me figure this out?

Saturday, 28 September 2013

How to fix NullPointerException in Java?

How to fix NullPointerException in Java?

I'm creating a math program that asks the user how many digits they'd like
to use, then asks them what kind of math they want to do. It then asks the
user 10 math questions based on their answers. It then decides if they're
right or wrong and displays an appropriate message. It then calculates
their percentage of correct answers and displays a message based on the
percentage.
I seem to have the math logic working, but as soon it loops into the
second question, I get a NullpointerException.
I've never run into this issue before, but what I gathered from searching
around is that it means that I'm trying to use an object that has a null
value (not 100% on this?). Can anyone tell me why this code would work
fine the first time around, but then throw this exception the second time
around?
Thanks for any help.
Exception in thread "main" java.lang.NullPointerException at
assignment2.Assignment2.askQuestion(Assignment2.java:104) at
assignment2.Assignment2.main(Assignment2.java:43)
Line 104 reads
operatorText = (selectedOperator == 5) ? operators[(int)
Math.floor(Math.random() * operators.length)] : operators[selectedOperator
- 1];
Line 43 reads
askQuestion(0, null, 0, 0, null, 0);
Full code
import java.util.*;
import javax.swing.JOptionPane;
/**
*
*/
/**
* @author Tyler
*
*/
public class Problem2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int difficulty = 1;
String[] operators = {"plus", "minus", "times",
"divided by"};
int selectedOperator = 1;
int correctAnswers = 0;
int answeredTyped = 0;
int difficultyInput =
Integer.parseInt(JOptionPane.showInputDialog("Please
choose the difficulty. Enter the number of digits to
use in each problem."));
if (difficultyInput > 0) {
difficulty = difficultyInput;
}
int arithmeticMethod =
Integer.parseInt(JOptionPane.showInputDialog("Choose an arithmetic
problem to study: 1 = Addition Only, 2 = Subtraction Only, 3 =
Multiplication Only, 4 = Division Only, 5 = Random Problems" ));
selectedOperator = arithmeticMethod;
new Problem2().askQuestion(difficulty, null, arithmeticMethod,
arithmeticMethod, operators, arithmeticMethod);
while(answeredTyped < 10){
askQuestion(0, null, 0, 0, null, 0);
if(((float)correctAnswers / answeredTyped) >= 0.75) {
JOptionPane.showMessageDialog(null, "Congratulations,
you are ready to go on to the next level!");
}
else{
JOptionPane.showMessageDialog(null, "Please
ask your teacher for extra help.");
}
}
}
public static boolean checkResponse (double primaryInt, double
secondaryInt, String operatorText, double response){
if (operatorText.equals("plus")){
return (primaryInt + secondaryInt) == response;
}
else if (operatorText.equals("minus")){
return (primaryInt - secondaryInt) == response;
}
else if (operatorText.equals("times")){
return (primaryInt * secondaryInt) == response;
}
else if (operatorText.equals("divided by")){
return (primaryInt / secondaryInt) == response;
}
return false;
}
public static String displayResponse (boolean isCorrect){
int randomIndex = (int) (Math.floor(Math.random() * (4 - 1 +
1)) + 1);
switch (randomIndex){
case 1:
return isCorrect ? "Very Good!" : "No. Please try
again.";
case 2:
return isCorrect ? "Excellent!" : "Wrong. Try once
more.";
case 3:
return isCorrect ? "Nice Work!" : "Don\'t give up!";
case 4:
return isCorrect ? "Keep up the good work!" : "No.
Keep trying.";
}
return "Oops...";
}
public static void askQuestion(int difficulty, String
operatorText, int selectedOperator, int answeredTyped,
String[] operators, int correctAnswers){
boolean correctAnswer = false;
double primaryInt = Math.floor(Math.pow(10,
difficulty-1) + Math.random() * 9 * Math.pow(10,
difficulty-1));
double secondaryInt = Math.floor(Math.pow(10,
difficulty-1) + Math.random() * 9 * Math.pow(10,
difficulty-1));
operatorText = (selectedOperator == 5) ?
operators[(int) Math.floor(Math.random() *
operators.length)] : operators[selectedOperator - 1];
while(!correctAnswer && answeredTyped < 10) {
double response = Double.parseDouble
(JOptionPane.showInputDialog("How much is " +
primaryInt + " " + operatorText + " " +
secondaryInt + "?"));
correctAnswer = checkResponse (primaryInt,
secondaryInt, operatorText, response);
JOptionPane.showMessageDialog(null,
displayResponse(correctAnswer));
answeredTyped++;
if(correctAnswer)
correctAnswers++;
}
}
}

Trouble with CSS Hover and Active

Trouble with CSS Hover and Active

I'm working on a project for my intro to web design class and I've hit a
wall. I'm trying to change the image of the button when its on hover and
active, currently it will show the button but when you go to hover over it
doesn't change, I've tried giving the buttons there own id as well as just
replacing the current image with another but it doesn't work.
html:
<div id="navcontainer" class="column five">
<ul id="navmain">
<li><a href="index.html" id="home">Home</a></li>
<li><a href="philosophy.html" id="btnphil">Philosophy</a></li>
<li><a href="econews.html" id="btnnews">Eco News</a></li>
<li><a href="diy.html" id="btndiy">DIY</a></li>
<li><a href="takeaction.html" id="btntake">Take Action
</a></li> </ul>
</div><!-- .sidebar#sideLeft -->



CSS:
#navcontainer{
padding:10px 30px;
width:220px;
float: left;
margin-top:480px;
}
#navmain li{
list-style:none;
}
#navmain li, #navmain a{
text-decoration:none;
height:38px;
width:153px;
background-image: url('../images/button.png') ;
background-position: center;
text-align: center;
color:#000;
margin-left:-10px;
margin-top:20px;
vertical-align: -22%;
#navmain, #home a:hover {
text-decoration:none;
height:38px;
width:153px;
background-image: url('../images/buttonhover.png') ;
background-position: center;
text-align: center;
color:#000;
margin-left:-10px;
margin-top:20px;;}
}
#navmain a:active {
border-top-color: #297ab0;
background: #297ab0;
}

jQuery's .hide() not working

jQuery's .hide() not working

I don't know why the function .hide() is not hiding my div #cargando when
the div #tabla finishes loading.
<script>
$(window).load(function () {
$(function () {
var url = this.href;
$("#tabla").load(url, function () {
$('#cargando').hide();
});
});
});
</script>

Storeprocedure that filter, sort, support paging and do some extra functionality on the resultset

Storeprocedure that filter, sort, support paging and do some extra
functionality on the resultset

I'm looking for an expert advice to fine tune the sample stored procedure
for performance gain as well as to follow best practices.
To explain my requirements I have created a sample procedure below. The
procedure need to do the following
Need to filter based on the parameters.
Sort the data based on the @SortExpression eg. Code Desc or ImpDate ASC
Return total record count of entire record set.
Return totals of a field in the entire record set .
finally return only a subset of record set based on the startRowIndex and
page size
CREATE PROCEDURE [dbo].[_getlist](@CompanyID VARCHAR(10),
@IsPaid VARCHAR(3),
@Code VARCHAR(10) = NULL,
@ImpDate DATETIME = NULL,
@BatchNo INT,
@StartRowIndex INT,
@PageSize INT,
@SortExpression VARCHAR(50),
@TotalAmount NUMERIC(15, 2) output,
@RecordCount INT output)
AS
BEGIN
DECLARE @SortDirection VARCHAR(10)

SET @SortDirection = 'ASC'

IF RIGHT(@SortExpression, 5) = ' DESC'
SET @SortDirection = 'DESC'

DECLARE @SortColumn VARCHAR(50)

SELECT @SortColumn = Replace(@SortExpression, ' ASC', '')

SELECT @SortColumn = Replace(@SortColumn, ' DESC', '')

DECLARE @StartIndex INT,
@EndIndex INT

SET @StartIndex = @StartRowIndex
SET @EndIndex = @StartRowIndex + @PageSize -- (@CurrentPage + 1 )
SELECT data.,
Row_number()
OVER (
ORDER BY CASE WHEN @SortDirection = 'DESC' THEN CASE WHEN
@SortColumn
=
'code' THEN data.client_code END END DESC, CASE WHEN
@SortDirection
=
'ASC'
THEN CASE WHEN @SortColumn = 'code' THEN data.client_code
END END
ASC )
AS
RowNumber
INTO #temptable
FROM (SELECT *
FROM clients
WHERE is_local = 'Yes'
AND is_paid = 'No'
AND status = 'Valid'
AND ( company_id = @CompanyID )
AND ( ispaid = @IsPaid
OR @IsPaid IS NULL )
AND ( code = @Code
OR @Code IS NULL )
AND ( @ImpDate IS NULL
OR import_date = @ImpDate )
AND ( @BatchNo = 0
OR batch_no = @BatchNo )) AS data

SELECT @RecordCount = Count(*)
FROM #temptable

SELECT @TotalAmount = Sum(total_tax)
FROM #temptable

SELECT *
FROM #temptable
WHERE rownumber >= @StartIndex
AND ( rownumber <= @EndIndex
OR @PageSize = -1 )

DROP TABLE #temptable
END
The sample is just to explain the requirements. I really appreciate any
help that could help me out.
Thanks,

Friday, 27 September 2013

figuring out how to find the average of entered numbers

figuring out how to find the average of entered numbers

I need help figuring out how to find the average of entered numbers with
this code that i wrote:
sum = 0.0
average = number / sum
data = input("Enter a number or enter 999 to quit: ")
while data != "999":
number = float(data)
sum += number
data = input("Enter a number or enter 999 to quit: ")
print("The sum is", average)

Data not saved OR nor fetched correctly with Core Data on iOS 7

Data not saved OR nor fetched correctly with Core Data on iOS 7

I'm experiencing a very weird problem with iOS Core Data behaviour. I have
code that uses Core Data in iOS 6 and everything works just fine. When I'm
running the same code on iOS 7, when fetching the data from the DB I get
empty results.
I know that Apple changed the Core Data default to WAL and I set the
options back to DELETE mode but I still get nothing.
Any ideas? Something else got changed on iOS 7?
Thanks!

Swing: jlabel+jcombox+jtextfield

Swing: jlabel+jcombox+jtextfield

I need to build a jlabel next to a jcombobox next to a jtextfield.
JTextfield must be accepting only numbers. The text from jtextfield should
be stored in a string and the element chosen also stored in a different
string. Also it would be ideal if i could add a jbutton so that all the
selections to be parsed when the button is clicked. I am currently using
this unfinished code, but it wont work. Can someone suggest the required
additions? Thanks in advance
public class constraints {
private static JTextField tField;
private MyDocumentFilter documentFilter;
private JLabel amountLabel;
private static String amountString = "Select Quantity (in ktones): ";
public static String str = "" ;
private void displayGUI()
{
JFrame frame = new JFrame("Constraints");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
amountLabel = new JLabel(amountString);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
tField = new JTextField(10);
amountLabel.setLabelFor(tField);
String[] petStrings = { "Less", "Equal", "More"};
JComboBox petList = new JComboBox(petStrings) ;
petList.setSelectedIndex(3);
petList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JComboBox cb = (JComboBox)event.getSource();
String petName = (String)cb.getSelectedItem();
System.out.println("petName");
}
});
((AbstractDocument)tField.getDocument()).setDocumentFilter(
new MyDocumentFilter());
contentPane.add(amountLabel);
contentPane.add(petList);
contentPane.add(tField);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
@Override
public void run()
{
new constraints().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class MyDocumentFilter extends DocumentFilter
{
@Override
public void insertString(DocumentFilter.FilterBypass fp
, int offset, String string, AttributeSet aset)
throws BadLocationException
{
int len = string.length();
boolean isValidInteger = true;
for (int i = 0; i < len; i++)
{
if (!Character.isDigit(string.charAt(i)))
{
isValidInteger = false;
break;
}
}
if (isValidInteger)
super.insertString(fp, offset, string, aset);
else
Toolkit.getDefaultToolkit().beep();
}
@Override
public void replace(DocumentFilter.FilterBypass fp, int offset
, int length, String string, AttributeSet aset)
throws BadLocationException
{
int len = string.length();
boolean isValidInteger = true;
for (int i = 0; i < len; i++)
{
if (!Character.isDigit(string.charAt(i)))
{
isValidInteger = false;
break;
}
}
if (isValidInteger)
super.replace(fp, offset, length, string, aset);
else
Toolkit.getDefaultToolkit().beep();
}
}

hg update over ssh not working (hg clone works well...)

hg update over ssh not working (hg clone works well...)

I have some code on bitbucket.org under mercurial version control. Now I
want to download the code on my ubuntu machine over ssh. When I use hg
clone everything works well. However hg update never updates any files.
I'm not even asked for my ssh password. I checked these setting:
ssh -v hg@bitbucket.org
-> looks ok.
hg showconfig
-> path.default = ssh://hg@bitbucket.org/user/myrepo...
Do you have any idea what else to check?
Thanks.

GitHub webhook direct ip

GitHub webhook direct ip

I'm trying to use Webhook (in GitHub) to make deployment to several ip
addresses (AWS Instances) and it's not working. If i'm using domain name
it works fine. What i'm doing wrong?

Thursday, 26 September 2013

How to access values from dynamically added user control?

How to access values from dynamically added user control?

I want to get values from dynamically added user control
I'm trying but count comes as 0 so condition failed
Code:
private const string VIEWSTATEKEY = "ContactCount";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Set the number of default controls
ViewState[VIEWSTATEKEY] = ViewState[VIEWSTATEKEY] == null ? 1
: ViewState[VIEWSTATEKEY];
//Load the contact control based on Vewstate key
LoadContactControls();
}
}
private void LoadContactControls()
{
for (int i = 0; i < int.Parse(ViewState[VIEWSTATEKEY].ToString()); i++)
{
rpt1.Controls.Add(LoadControl("AddVisaControl.ascx"));
}
}
protected void addnewtext_Click(object sender, EventArgs e)
{
ViewState[VIEWSTATEKEY] =
int.Parse(ViewState[VIEWSTATEKEY].ToString()) + 1;
LoadContactControls();
}
Here is the problem count takes as 0 so condition failed loop comes out
private void saveData()
{
for (int i = 0; i < this.rpt1.Controls.Count; i++)
{
if (this.rpt1.Controls[i] is TextBox)
{
TextBox txtserial = (TextBox)this.rpt1.Controls[i];
string value = txtserial.Text;
}
}
}
protected void Save_Click(object sender, EventArgs e)
{
saveData();
}
.ascx
<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="AddVisaControl.ascx.cs" EnableViewState="false"
Inherits="Pyramid.AddVisaControl" %>
<%@ Register assembly="BasicFrame.WebControls.BasicDatePicker"
namespace="BasicFrame.WebControls" tagprefix="BDP" %>
<div id="divreg" runat="server">
<table id="tbl" runat="server">
<tr>
<td>
<asp:Label ID="lbl2" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td> Visa Number:</td>
<td><asp:TextBox ID="txtUser" Width="160px" runat="server"/></td>
<td> Country Name:</td>
<td><asp:DropDownList ID="dropCountry" Width="165px"
runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Type of Visa:</td>
<td><asp:DropDownList ID="dropVisa" Width="165px"
runat="server"></asp:DropDownList></td>
<td> Type of Entry:</td>
<td><asp:DropDownList ID="dropEntry" Width="165px"
runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Expiry Date</td>
<td><BDP:BasicDatePicker ID="basicdate"
runat="server"></BDP:BasicDatePicker></td>
<td>
<asp:Button ID="btnRemove" Text="Remove" runat="server"
OnClick="btnRemove_Click" />
</td>
</tr>
</table>
</div>
Any ideas? Thanks in advance

Thursday, 19 September 2013

Default value initialization in a default move constructor

Default value initialization in a default move constructor

Given an example class:
class Foo
{
int x = 0;
...
public:
Foo (Foo &&) = default;
...
};
The default constructor will be implemented as:
Foo::Foo () : x (0), ... { ... }
Is the default initialization value honoured by the explicitly defaulted
move constructor? i.e., implemented as:
Foo::Foo (Foo && f) : x (f.x), ... { f.x = 0; ... }
Furthermore, if the move constructor is implemented (not defaulted), and x
is omitted from the initializer list, will it still be initialized to the
default (0) value? i.e.,
Foo::Foo (Foo && f) : ... { f.x = 0; } // will (x) be (0) ?

Equation for Length of Cubic Spline Between 3 Points

Equation for Length of Cubic Spline Between 3 Points

This is my first time posting here, so I hope this is ok. I'm working on a
java project but my question is really about the math I'll be using for
it...
I have three (different) points at (x1, y1), (x2, y2), and (x3, y3). All I
need is a formula for the length of the cubic spline formed between them.
For someone good at calculus, this should be pretty easy to derive. I've
looked all around online but can't seem to find the solution. Again, I
don't even need the equation of the spline - just its length, given the
three points. Thanks in advance! If someone can figure this out and share,
you'll makey day :)

Setting an email to delete automatically after a time period

Setting an email to delete automatically after a time period

I am looking to send emails that will delete after a given amount of time
at their destination, giving them only a certain amount of time to
respond. I will be sending these emails to people who have different email
clients, so a client side solution seems impossible. Is there any sort of
way to do this?

Calling custom phonegap plugin gives error "Uncaught ReferenceError: calendar is not defined"

Calling custom phonegap plugin gives error "Uncaught ReferenceError:
calendar is not defined"

I am creating a phonegap test project with custom calendar plugin
published here. When I call it on device ready, I get "Uncaught
ReferenceError: calendar is not defined" error. I have published the code
on github. Here's the link if you want to take a look. Thanks in advance
for help.

Adding UIViewcontrollers to UIScrollview

Adding UIViewcontrollers to UIScrollview

I am changing the layout of an existing application. There are a series of
view which now needs to be added to a scrollview that the users can swipe
to move to next screen. I have added the controllers to scrollview using
the code below.
This code is added in the viewDidLoad of the Viewcontroller which holds
the UIScrolliew
..
int i=1;
int width = 0,height=0;
for(POTCTask *task in [CommonData tasks])
{
UIViewController<TaskViewController> *controller = [TaskViewFactory
getTaskViewController:(task.inputTypeId)];
width = controller.view.frame.size.width;
height = controller.view.frame.size.height;
controller.view.frame = CGRectMake(width*(i-1), 0, width, height);
[self.scrollView addSubview:controller.view];
i++;
}
self.scrollView.contentSize = CGSizeMake(width*i, height);
It loads all view fine. But only the viewDidLoad is getting called in each
viewcontroller. No other methods are getting called And some have
UItableviews in it. But its showing only the first cell.
How can I do this properly in ios?
Thanks

could not connect to smtp host for gmail in php mailer?

could not connect to smtp host for gmail in php mailer?

I am using php mailer extension in yii framework to send mail. when i
configured smtp with my authenticated gmail user name and password and
send mails, everything working fine in my localhost(Wamp server). When i
hosted it into my server and tested sending mail, i was successfully able
to send mail for smtp.live.com and smtp.mail.yahoo.com but i get a error
"Could not connect to smtp host".
How to fix it?
Also what should happen when i give smtpAuth = false and try to send mail?
I was not able to send mail if my smtpAuth is false. Should i need to give
username and password even for smtpAuth = false?

How to define a ItemTemplate for GridView (inside a ListView) so it can be used mu different ListView?

How to define a ItemTemplate for GridView (inside a ListView) so it can be
used mu different ListView?

The question is quite straightforward but I just can't neither find an
example nor figure it out by myself.
My requirement is I have some ListView, which bind to some collections in
the ViewModel. The type of items in those collections are the same (let's
called TypeA), which is a class exposing multiple simple type properties.
So I would like to display them in a GridView inside those ListView. And
naturally I would want to define a DataTemplate for this TypeA, so that I
don't need to write the same long xaml code, because I have for example
many header properties defined for the GridViewColumn. All of the examples
are to define the ItemTemplate inside the ListView. How can I make a
resource and let different ListView refer to this resource?

how to allocate dynamic memory to an array when number of element is unknown in C

how to allocate dynamic memory to an array when number of element is
unknown in C

How to allocate dynamic memory to an array where size or number of element
is unknown
int *p = (int*)malloc(i*sizeof(int)); here i also dynamic mean i may be 1
or 1000 we don't know so how to allocate size thanks

Wednesday, 18 September 2013

how to unselect a devexpress data grid row when we click with ctrl+ mouse left button wpf

how to unselect a devexpress data grid row when we click with ctrl+ mouse
left button wpf

I have a devexpress data grid with data. I am able to select multiple rows
and on button click I am unselecting all the rows perfectly. but the
problem is I am unable to deselect the row with ctrl+mouse left click.
actually the row is getting deselected, when I check the visiblerowcount
value, but in the UI it is still showing as selected row.
How can I do unselection? this is the code for selecting all the rows of
my grid
MyGrid.TableView.SelectAll();
SelectedRecords.Text = "" + MyGridVisibleRowCount;
and for unselection all the rows on button click I am doing in this way
MyGrid.ClearSelection();
MyGrid.View.FocusedRowHandle = -1;
SelectedRecords.Text = "" + 0;
any help highly appericated.
Thanks Ganesh

Configuring a mysql table or query to meet these needs

Configuring a mysql table or query to meet these needs

Okay so I have gotten the gist of most of mysql query and how to set-up my
table however I am a little lost on how I can do this.
I currently have a table that has this format:
tag_target_id | tag_id | sub_tag_id | tag_target_name | tag_type_id
int(11) | int(11) | int(11) | varchar(255) | int(11
<PK> | <FK> | <FK> | | <FK>
A single tag_target_id corresponds to one piece of content ie. a video,
article etc. now in the table there should be multiple entries with the
same tag_target_id and tag_target_name and different tag_id , sub_tag_id ,
tag_type_id simple enough
So my problem is when I am inserting data into the table I have a PDO
query that looked like this:
"INSERT INTO phpro_tag_targets (tag_id, sub_tag_id, tag_target_name,
tag_type_id)
VALUES (:tag_id, :sub_tag_id,:tag_target_name,:tag_type_id)"
... I used to have tag_target_id as auto increment however each new query
obviously incremented the tag_target_id so a single piece of content would
have tag-target_id = 5, 6, 7, 8, 9 for eg. where I would like to have each
piece of new content have one single tag_target_id
Now I would like to somehow have each new piece of content have a new
tag_target_id but not each entry into the table for a single piece of
content have it's own unique idea
so for eg. for one piece of content in the table all data for that content
could look like this:
tag_target_id | tag_id | sub_tag_id | tag_target_name | tag_type_id
int(11) | int(11) | int(11) | varchar(255) | int(11
54 | 22 | 64 | url_to_content | 16
54 | 66 | 82 | url_to_content | 24
54 | 22 | 77 | url_to_content | 18
54 | 87 | 55 | url_to_content | 16
54 | 66 | 92 | url_to_content | 20
So how can I change the structure of the table or write a query set to
achieve this desired output? Thanks in advance for any advise or help with
this!

Playframework 2.0 in IntelliJ IDEA File Association

Playframework 2.0 in IntelliJ IDEA File Association

What's the right file type for IDEA to pick up the Play Framework Routes
file?

When Debugging in Java, is there a way to detect if ANY variable is set to a given value?

When Debugging in Java, is there a way to detect if ANY variable is set to
a given value?

I have a very large app that takes a value and makes it disappear
SOMEWHERE and I want to see where it is going. So what I'm looking for the
is the value of the variable so I can find out what variable is holding
it. I'm hoping there is some sort of technique, possibly involving a
classloader or reflection?

How to sum time of two rows in sql server

How to sum time of two rows in sql server

1 Med1 2013-09-10 ec2700 Karthiga G Audits Centricity - Charge
Audit 2013-05-21 W6 61 01:28:27.0000000
2 Med1 2013-09-10 ec2700 Karthiga G Miscellaneous Other
Periodical or special adjustments 2013-05-21 W6 108 02:36:36.0000000
3 Med1 2013-09-10 ec2700 Karthiga G Miscellaneous # of rows
updated in Audit Log 2013-05-21 W6 61 00:20:20.0000000
4 Med1 2013-09-10 ec2700 Karthiga G Miscellaneous # of Errors
identified/updated in Audit Log 2013-05-21 W6 4 00:08:08.0000000
40 Med1 2013-09-11 ec2700 Karthiga G Audits Centricity - Charge
Audit 2013-05-21 W6 37 00:53:39.0000000
41 Med1 2013-09-11 ec2700 Karthiga G Miscellaneous Other
Periodical or special adjustments 2013-05-21 W6 244 05:53:48.0000000
42 Med1 2013-09-11 ec2700 Karthiga G Miscellaneous # of rows
updated in Audit Log 2013-05-21 W6 37 00:12:20.0000000
43 Med1 2013-09-11 ec2700 Karthiga G Miscellaneous # of Errors
identified/updated in Audit Log 2013-05-21 W6 1 00:02:02.0000000
184 Med1 2013-09-12 EC2700 Karthiga G Audits Centricity - Charge
Audit 2013-05-21 W6 27 00:39:09.0000000
185 Med1 2013-09-12 EC2700 Karthiga G Miscellaneous Other
Periodical or special adjustments 2013-05-21 W6 264 06:22:48.0000000
186 Med1 2013-09-12 EC2700 Karthiga G Miscellaneous # of rows
updated in Audit Log 2013-05-21 W6 27 00:09:00.0000000
343 Med1 2013-09-13 ec2700 Karthiga G Charges NTP - Import Charge
Entry 2013-05-21 W6 30 01:16:30.0000000
344 Med1 2013-09-13 ec2700 Karthiga G Audits Centricity - Charge
Audit 2013-05-21 W6 49 01:11:03.0000000
345 Med1 2013-09-13 ec2700 Karthiga G Miscellaneous # of rows
updated in Audit Log 2013-05-21 W6 49 00:16:20.0000000
354 Med1 2013-09-13 ec2700 Karthiga G Miscellaneous Other
Periodical or special adjustments 2013-05-21 W6 57 01:22:39.0000000
508 Med1 2013-09-14 ec2700 Karthiga G Charges NTP - Import Charge
Entry 2013-05-21 W6 100 04:15:00.0000000
510 Med1 2013-09-14 ec2700 Karthiga G Audits Centricity - Charge
Audit 2013-05-21 W6 53 01:16:51.0000000
511 Med1 2013-09-14 ec2700 Karthiga G Miscellaneous # of rows
updated in Audit Log 2013-05-21 W6 53 00:17:40.0000000
604 Med1 2013-09-16 ec2700 Karthiga G Audits Centricity - Charge
Audit 2013-05-21 W6 39 00:56:33.0000000
605 Med1 2013-09-16 ec2700 Karthiga G Charges NTP - Import Charge
Entry 2013-05-21 W6 96 04:04:48.0000000
606 Med1 2013-09-16 ec2700 Karthiga G Payments NTP - Payment
Entry 2013-05-21 W6 14 00:25:54.0000000
607 Med1 2013-09-16 ec2700 Karthiga G Miscellaneous Un-assigned /
Copay Payment Posting 2013-05-21 W6 134 01:24:52.0000000
738 Med1 2013-09-17 EC2700 Karthiga G Charges NTP - Import Charge
Entry 2013-05-21 W6 102 04:20:06.0000000
739 Med1 2013-09-17 EC2700 Karthiga G Payments NTP - Payment
Entry 2013-05-21 W6 32 00:59:12.0000000
740 Med1 2013-09-17 EC2700 Karthiga G Audits Centricity - Charge
Audit 2013-05-21 W6 40 00:58:00.0000000
741 Med1 2013-09-17 EC2700 Karthiga G Miscellaneous Un-assigned /
Copay Payment Posting 2013-05-21 W6 136 01:26:08.0000000
742 Med1 2013-09-17 EC2700 Karthiga G Miscellaneous # of rows
updated in Audit Log 2013-05-21 W6 40 00:13:20.0000000
933 Med1 2013-09-18 ec2700 Karthiga G Charges NTP - Import Charge
Entry 2013-05-21 W6 105 04:27:45.0000000
934 Med1 2013-09-18 ec2700 Karthiga G Payments NTP - Payment
Entry 2013-05-21 W6 48 01:28:48.0000000
935 Med1 2013-09-18 ec2700 Karthiga G Miscellaneous Other
Periodical or special adjustments 2012-01-01 W6 88 02:07:36.0000000

Facebook Latest Post using Facebook API

Facebook Latest Post using Facebook API

I want to get all the latest posts from facebook posted from Boston.
I searched in google but not found any solution for this.
I tryed fql
SELECT id FROM location_post WHERE latitude = 20.0 AND longitude = 86.0
This is showing error.
{
"error": {
"message": "(#601) Parser error: unexpected '.' at position 48.",
"type": "OAuthException",
"code": 601
}
}
but in example its give like this
https://developers.facebook.com/docs/reference/fql/location_post
can you please help to solve this one.
thanks in advance

Build project with h323plus lib, using Qt

Build project with h323plus lib, using Qt

I built h323plus and PWLib using msvc 2008. Then I built samples and it
works fine, but now I need to use this libs with Qt. Using msvc I'm adding
include directories, lib directories and also libs which I want to add to
project. It is enough to make work the following code:
#include <ptlib.h>
#include <h323.h>
class SimpleClass : public PProcess
{
PCLASSINFO(SimpleClass, PProcess)
public:
void Main()
{
std::cout << "Hello World" << std::endl;
}
};
PCREATE_PROCESS(SimpleClass)
I'm trying to do same actions using Qt (MinGW). I added INCLUDEPATH and
LIBS to .pro file. It seems it included correctly. But I have a lot of
errors:
C:\Qt\projetcs\test1\main.cpp:16: error: undefined reference to
`PProcess::PreInitialise(int, char*, char*)'
I believe the header was found and successfully included, but I don't
understand why PProccess functions were not founded. It's maybe need to
define some flags or have special config for compiler. What am I doing
wrong?

Tuesday, 17 September 2013

Is it possible to instantiate an array of variable lengths with indices of all -1 in JAVA?

Is it possible to instantiate an array of variable lengths with indices of
all -1 in JAVA?

Is it possible to create an integer array i with a variable length k,
where all indices are some specified value, say -1?
I know I could do something like:
int[] i = new int[k];
for (int a = 0; a < k; a++) {
i[a] = -1;
}
Are there any short-cuts that would not require the for-loop?

Wordpress Syntax Error, unexpected [

Wordpress Syntax Error, unexpected [

I have a problem with a wordpress installation. When I work locally, this
function works properly:
function get_images_from_media_library() {
$args = array(
'post_type' => 'attachment',
'post_mime_type' =>'image',
'numberposts' => -1,
'post_status' => null,
'post_parent' => null, // any parent
);
$attachments = get_posts($args);
$images = array();
if ($attachments) {
foreach ($attachments as $post) {
setup_postdata($post);
array_push($images, wp_get_attachment_image_src($post->ID,
'full')[0]);
}
}
return $images;
}
This retrieves all the images attached to media on the installation and
returns them in an array.
However, when I put my installation up on my remote site, I get this error
when I try to use the theme that holds this function:
Parse error: syntax error, unexpected '[' in
/hermes/bosoraweb133/b2623/ipg.yourdomaincom/98EMcBee/wp-content/themes/98emcbee/functions.php
on line 52
Line 52 is this line inside the foreach:
array_push($images, wp_get_attachment_image_src($post->ID, 'full')[0]);
Why would I get this error on a remote site and not on a local site?

Perl - multiple keys and merging two files

Perl - multiple keys and merging two files

I'm not a regular coder but some times I write some basic perl script,
hence Perl is bit difficult for me .
I'm merging two files a.txt and b.txt into c.txt:
a.txt
------
x001;frtb70;xyz;109
x001;frvt65;sec;239
x003;wqax34;jul;659
x004;yhud43;yhn;760
b.txt
------
x001;abcd80;xyz;193
x001;crrp28;xse;456
x002;lmno10;xyz;784
x002;jfds65;jfd;739
x002;juop88;jup;879
x003;yulo90;rem;542
x003;kihl98;dnt;312
x004;urel25;ewb;342
c.txt [output]
------
x001;frtb70;xyz;109
x001;frvt65;sec;239
x002;lmno10;xyz;784
x002;jfds65;jfd;739
x003;wqax34;jul;659
x004;yhud43;yhn;760
Only condition is: I need all the lines from a.txt into c.txt. But while
selecting lines from b.txt into c.txt, first I need to look into a.txt. If
the line is already present in a.txt, then I shouldn't consider that b.txt
line while writing into c.txt [output]. In all the files, we can consider
first column as key, but it may contain duplicates. That is becoming
challenge for me.
Below are the script I've writen. problem is, as I'm using hash for both
input files, its not considering the lines which has same key value. But I
should use all a.txt eventhough keys are same. Same is true for b.txt,
except it should skip the lines, if the key is already present in a.txt.
#!/usr/bin/env perl
sub prepareHash {
#my ($in_file, $primary_Key, $delimiter) = @_;
my $in_file = shift;
my $key = shift;
my $delimiter = shift;
my @line_tokens;
my %FILE_Hash;
open( IN_FILE, "< $in_file" ) or die "Can't open $in_file : $!";
while (<IN_FILE>) {
my $in_line = $_;
chomp($in_line);
@line_tokens = split(/$delimiter/, $in_line);
$FILE_Hash{$line_tokens[$key]} = $in_line;
}
close IN_FILE;
return %FILE_Hash;
}
my $input1 = "/export/home/a.txt";
my $input2 = "/export/home/b.txt";
my $output = "/export/home/c.txt";
my %A_Hash = prepareHash($input1, 0 , ";" );
my %B_Hash = prepareHash($input2, 0 , ";" );
open( OUT_FILE, "> $c.txt" ) or die "Can't open $c.txt : $!";
for my $a_key ( sort keys %A_Hash ) {
$a_key =~ s/\s+$//;
my $a_line = $A_Hash{$a_key};
print OUT_FILE $a_line . "\n";
}
# Compare OBL and REPOOBL. Only write extra REPOOBL lines which are not
in OBL into BOND file
for my $b_key ( sort keys %B_Hash ) {
$b_key =~ s/\s+$//;
if ( ! exists $A_Hash{$b_key} ) {
my $b_line = $B_Hash{$b_key};
print OUT_FILE $b_line . "\n";
} else {
print "$B_Hash{$b_key} is the already writen into c.txt using a.txt,
hence skipping\n";
}
}
close OUT_FILE;
Can any of you help me please?

Images on RSS Feed app

Images on RSS Feed app

With android studio I wrote the code to get news. I've written that one
for the title, the description and the pubdate, the only thing is that i
want to add the images too. How can i do? This is the java class
public class MainActivity extends ListActivity {
private RSSFeed myRssFeed = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
try {
URL rssUrl = new URL("http://lfjdlhnvdflonhdxf.xml");
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
myRssFeed = myRSSHandler.getFeed();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (myRssFeed!=null)
{
ArrayAdapter<RSSItem> adapter =
new ArrayAdapter<RSSItem>(this,
android.R.layout.simple_list_item_1,myRssFeed.getList());
setListAdapter(adapter);
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(this,ShowDetails.class);
Bundle bundle = new Bundle();
bundle.putString("keyTitle", myRssFeed.getItem(position).getTitle());
bundle.putString("keyPsi", myRssFeed.getItem(position).getDescription());
bundle.putString("keyPubdate", myRssFeed.getItem(position).getPubdate());
intent.putExtras(bundle);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

C++ Help Separating one .cpp file into several .cpp and .h files

C++ Help Separating one .cpp file into several .cpp and .h files

I am working on a project now that requires to take one .cpp file and
seperate it into other .cpp files and .h I have been working on this
project for several weeks now and im always getting stuck on it. Thank you
very much
#include <cstdlib>
#include <sys/types.h>
#include <ctime>
#include <iostream>
#include <string>
using namespace std;
/**
* A cookie in the game of chomp. A cookie is begins as
* a rectangular arrangement of "crumbs". We can then take
* bites at specific locations. A byte at (x,y) eliminates the
* crumb at that location and all crumbs below and to the right
* For example, given a cookie
* %%%%
* %%%%
* %%%%
* %%%%
* a bite at (1,2) would leave:
* %%%%
* %%%%
* %
* %
* after which, a second bite at (2,1) would leave
* %%%%
* %%
* %
* %
*/
struct Cookie {
int initialNumberOfRows;
/// Number of rows currently remaining in the cookie
int numberOfRows;
/// Number of columns currently remaining in the cookie
int numberOfColumns;
/**
* The "shape" of the cookie.
*
* If crumbs[i] == j, then the cookie currently
* has crumbs filling the j columns at row i
*/
int* crumbs;
};
struct Player {
std::string name;
int numGamesWon;
};
struct Game {
/// The cookie for this game.
Cookie cookie;
};
Player computer = {"computer", 0};
Player human = {"", 0};
/**
* Number of non-empty rows currently remaining in the cookie
* (value decreases as we continue to take bites)
*
* @param cookie the cookie
* @return number of non-empty rows in the cookie
*/
int getNumberOfRows(const Cookie& cookie);
/**
* The number of rows remaining in a specific column
* @param cookie the cookie
* @param colNum a column number in the cookie
* @return number of non-empty rows remaining in that column
*/
int getNumberOfRows(const Cookie& cookie, int colNum);
/**
* Number of non-empty columns currently remaining in the cookie
* @param cookie the cookie
* @return number of non-empty columns
*/
int getNumberOfColumns(const Cookie& cookie);
/**
* The number of columns remaining in a specific row
* @param cookie a cookie
* @param rowNum a row
* @return number of non-empty columns in that row
*/
int getNumberOfColumns(const Cookie& cookie, int rowNum);
/**
* Determines if a proposed bite by the computer player could allow
* a skillful opponent to force a loss. *
* @param cookie current cookie
* @param column column of porposed bite
* @param row row of proposed byte
* @return true if choosing this bite could lead to a forced loss
*/
bool isADangerousMove (Cookie& cookie, int column, int row);
/**
* Remove the crumb at the indicated position an
* all crumbs below and to the right of that position.
* @param cookie cookie from which we want to take a bite
* @param column column of desired bite
* @param row row of desired biete
*/
void takeABite (Cookie& cookie, int column, int row);
/**
* Check a proposed move to see if it is legal.
* A legal move must bite at least one remaining crumb.
*
* @param g a game
* @param column x position of the desred bite
* @param row y position of the desired bite
* @return true iff this move is legal
*/
bool biteIsLegal (const Game& g, int column, int row)
{
return (column >= 0) && (row >= 0) && row < getNumberOfRows(g.cookie)
&& (column < getNumberOfColumns(g.cookie,row));
}
/**
* Release storage held by this cookie
*
* @param cookie cookie that is no longer needed
*/
void cleanUpCookie(Cookie& cookie)
{
delete [] cookie.crumbs;
}
/**
* Release any storage held by a game
*
* @param g a no-longer-needed game
*/
void cleanUpGame (Game& g)
{
cleanUpCookie(g.cookie);
}
/**
* Determines if the only legal move for the computer player
* is to bite the poison.
*
* @param cookie current cookie
* @param column proposed move - set to 0 if unavoidable
* @param row proposed move - set to 0 if unavoidable
* @param maxColumns original number of columns in the cookie
* @param lastNonEmptyRow highest numbered row containing a non-empty column
* @return true iff the computer player has to bite the poison
*/
bool computerPlayerMustLose
(Cookie& cookie, int& column, int& row,
int maxColumns, int lastNonEmptyRow)
{
if (getNumberOfColumns(cookie,0) == 1 && getNumberOfColumns(cookie,1)
== 0)
{
// We have to bite the poison crumb.
column = row = 0;
return true;
}
return false;
}
/**
* Determine if there is a move that can allow the computer player to
* force a win.
* @param cookie the cookie
* @param column output - column of the win-forcing move
* @param row output - row of the win-forcing move
* @param maxColumns remaining columns in this cookie
* @param lastNonEmptyRow highest numbered row that contains non-empty
columns
* @return true iff a move has been found that allows the computer to
force a win
*/
bool computerPlayerCanForceAWin
(Cookie& cookie,
int& column, int& row,
int maxColumns, int lastNonEmptyRow)
{
// We can force a win if there is only one row and that has
// more than one column
if (getNumberOfRows(cookie) == 1 && getNumberOfColumns(cookie,0) > 1)
{
column = 1;
row = 0;
return true;
}
// Or if there is only one column and that has more than one row
if (getNumberOfColumns(cookie) == 1 && getNumberOfRows(cookie) > 1)
{
column = 0;
row = 1;
return true;
}
// If row 0 is the only row with more than 1 column, and
// column 0 is the only column with more than 1 row, and the number of
// elements in each are different, then we can force an eventual win
// by evening them up.
if (getNumberOfRows(cookie) != getNumberOfColumns(cookie) &&
getNumberOfRows(cookie) > 1 &&
getNumberOfColumns(cookie) > 1 &&
getNumberOfColumns(cookie,1) == 1)
{
if (getNumberOfRows(cookie) > getNumberOfColumns(cookie))
{
column = 0;
row = getNumberOfColumns(cookie);
}
else
{
row = 0;
column = getNumberOfRows(cookie);
}
return true;
}
// More subtly, if we are down to two rows and the number of columns
// in each is different, we can force an eventual win by evening them
// up.
if (getNumberOfRows(cookie) == 2 && getNumberOfColumns(cookie,0) !=
getNumberOfColumns(cookie,1))
{
row = 0;
column = getNumberOfColumns(cookie,1);
return true;
}
// Or, if we are down to two columns and the number of rows
// in each is different, we can force an eventual win by evening them
// up.
if (getNumberOfColumns(cookie) == 2 &&
getNumberOfColumns(cookie,getNumberOfRows(cookie)-1) == 1)
{
column = 0;
row = 1;
while (getNumberOfColumns(cookie,row) == 2)
++row;
return true;
}
// If none of those are true, no obvious way to force a win
return false;
}
/**
* Display the cookie on the indicated output stream
* @param output where to show the cookie
* @param cookie the cookie to be shown
*/
void display (std::ostream& output, const Cookie& cookie)
{
// Print top line with numeric index of columns
output << ' ';
for (int col = 0; col < cookie.numberOfColumns; ++ col)
output << (col % 10);
output << endl;
// Print each row, preceded by a numeric row index
for (int row = 0; row < cookie.numberOfRows; ++row)
{
output << (row % 10);
for (int col = 0; col < cookie.crumbs[row]; ++col)
if (row == 0 && col == 0)
output << "P"; // (poison)
else
output << "*";
output << endl;
}
}
/**
* Check to see if the current game has been ended
* (i.e., has someone eaten the poison crumb?)
*
* @param g the game
* @return true iff the poison has been eaten
*/
bool gameEnded(const Game& g)
{
return getNumberOfColumns(g.cookie) <= 0;
}
/**
* Get the computer player's next move for this game.
*
* @param cookie cookie from which to choose the next move
* @param x x/column location of the next bite
* @param y y/row location of the next bite
*/
void getComputerPlayerMove (Cookie& cookie, int& column, int& row)
{
// Collect some basic info about the shape of the cookie
int maxColumns = getNumberOfColumns(cookie,0);
int lastNonEmptyRow = -1;
for (int r = 0; r < getNumberOfRows(cookie); ++r)
{
if (getNumberOfColumns(cookie,r) > maxColumns)
maxColumns = getNumberOfColumns(cookie,r);
if (getNumberOfColumns(cookie,r) > 0)
lastNonEmptyRow = r;
}
// If we can force a win, do it.
if (computerPlayerCanForceAWin(cookie, column, row, maxColumns,
lastNonEmptyRow))
{
cout << "You're not going to like this..." << endl;
return;
}
// If we are forced to lose, so be it.
if (computerPlayerMustLose(cookie, column, row, maxColumns,
lastNonEmptyRow))
{
cout << "Alas!" << endl;
return;
}
// Otherwise, choose a random move, but try to find one
// that is not obviously dangerous;
cout << "Hmm..." << endl;
const int LIMIT = 10;
row = rand() % lastNonEmptyRow;
column = rand() % getNumberOfColumns(cookie,row);
for (int attempt = 0; attempt < LIMIT
&& isADangerousMove(cookie, column, row);
++attempt)
{
row = rand() % lastNonEmptyRow;
column = rand() % getNumberOfColumns(cookie,row);
}
}
void getHumanPlayerMove (Cookie& cookie, int& column, int& row)
{
cout << "Your turn to take a bite from the cookie.\n";
cout << "Enter the column number and row number at which\n";
cout << " you wish to chomp (separated by a blank space): " << flush;
cin >> column >> row;
if (cin.fail()) {
cin.clear();
std::string junk;
getline(cin, junk); // discard rest of this input line
}
}
/**
* Number of non-empty columns currently remaining in the cookie
* @param cookie the cookie
* @return number of non-empty columns
*/
int getNumberOfColumns(const Cookie& cookie)
{
return cookie.numberOfColumns;
}
/**
* The number of columns remaining in a specific row
* @param cookie a cookie
* @param rowNum a row
* @return number of non-empty columns in that row
*/
int getNumberOfColumns(const Cookie& cookie, int rowNum)
{
return cookie.crumbs[rowNum];
}
/**
* Number of non-empty rows currently remaining in the cookie
* (value decreases as we continue to take bites)
*
* @param cookie the cookie
* @return number of non-empty rows in the cookie
*/
int getNumberOfRows(const Cookie& cookie)
{
return cookie.numberOfRows;
}
/**
* The number of rows remaining in a specific column
* @param cookie the cookie
* @param colNum a column number in the cookie
* @return number of non-empty rows remaining in that column
*/
int getNumberOfRows(const Cookie& cookie, int colNum)
{
int k = 0;
while (k < cookie.numberOfRows && cookie.crumbs[k] > colNum)
++k;
return k;
}
/**
* Set up a new cookie of random size
* @param cookie output - the cookie
*/
void initCookie(Cookie& cookie)
{
const int MAXROWS = 10;
// Randomply select size of the cookie, between 4 and MAXROWS
cookie.initialNumberOfRows = cookie.numberOfRows = 4 + rand() %
(MAXROWS - 4);
cookie.crumbs = new int[cookie.initialNumberOfRows];
cookie.numberOfColumns = cookie.numberOfRows;
while (cookie.numberOfColumns == cookie.numberOfRows)
cookie.numberOfColumns = 4 + rand() % (MAXROWS - 4);
for (int row = 0; row < cookie.numberOfRows; ++row)
cookie.crumbs[row] = cookie.numberOfColumns;
}
void initHumanPlayer(Player& human)
{
human.numGamesWon = 0;
cout << "Welcome to Chomp!\n"
<< "What is your name? "
<< flush;
getline (cin, human.name);
cout << "OK, " << human.name << ", let's play." << endl;
}
/**
* Create a new game with a cookie of random size
*
* @param g newly initialized game
*/
void initializeGame(Game& g)
{
initCookie (g.cookie);
cout << "The cookie has " << getNumberOfRows(g.cookie) << " rows of "
<< getNumberOfColumns(g.cookie) << " columns" << endl;
}
void initPlayer (Player& player, std::string name)
{
player.name = name;
player.numGamesWon = 0;
}
/**
* Determines if a proposed bite by the computer player could allow
* a skillful opponent to force a loss.
*
* @param cookie current cookie
* @param column column of porposed bite
* @param row row of proposed byte
* @return true if choosing this bite could lead to a forced loss
*/
bool isADangerousMove (Cookie& cookie, int column, int row)
{
// Always dangerous to eat the poison crumb
if (column == 0 && row == 0)
return true;
// Dangerous to leave only one row or one column unless
// it has only one element (the poison)
if (column == 0 && row > 1)
return true;
if (row == 0 && column > 1)
return true;
// Dangerous to take element (1,1) if the #rows and #cols are equal
if (row == 1 && column == 1 &&
getNumberOfRows(cookie) == getNumberOfColumns(cookie))
return true;
// Dangerous to take element (2,0) if the th remaining two rows
// are equal length
if (row == 2 && column == 0
&& getNumberOfColumns(cookie,0) == getNumberOfColumns(cookie,1))
return true;
// Dangerous to take element (2,0) if the the remaining two cols
// are equal length
if (row == 0 && column == 2
&& getNumberOfColumns(cookie, getNumberOfRows(cookie)-1) > 1)
return true;
return false;
}
/**
* Play an entire game
* @param game the game with an initialized cookie
* @param human human player
* @param computer computer player
*/
void playAGame(Game& game, Player& human, Player& computer)
{
while (!gameEnded(game))
{
display (cout, game.cookie);
// First, the human player's move
int xBite = -1;
int yBite = -1;
bool legalMove = false;
while (!legalMove)
{
getHumanPlayerMove (game.cookie, xBite, yBite);
legalMove = biteIsLegal (game, xBite, yBite);
if (!legalMove)
{
cout << "Sorry, but that is not a legal move." << endl;
}
}
takeABite (game.cookie, xBite, yBite);
if (gameEnded(game))
{
++computer.numGamesWon;
cout << "You have eaten the poison crumb! You lose." << endl;
}
else
{
// Computer player's move
display (cout, game.cookie);
getComputerPlayerMove (game.cookie, xBite, yBite);
cout << "I will chomp at column " << xBite
<< ", row " << yBite << "." << endl;
takeABite (game.cookie, xBite, yBite);
if (gameEnded(game))
{
++human.numGamesWon;
cout << "I had to eat the poison crumb. You win!"
<< endl;
}
}
}
}
void printScore(Player& human, Player& computer)
{
cout << "Score\tComputer: " << computer.numGamesWon
<< "\t" << human.name << ": " << human.numGamesWon
<< endl;
}
void printRules()
{
cout << "Chomp is a game played with a rectangular \"cookie\" made\n"
<< "up of square \"crumbs\".\n\n";
cout << "Taking turns, each player takes a bite from the cookie,\n"
<< "selecting a crumb that is removed from the cookie,
together\n"
<< "with all crumbs below and to the right of the selected
one.\n\n";
cout << "The top-left crumb in this cookie is poisoned. The player\n"
<< "who eats the poisoned crumb loses the game.\n" << endl;
}
/**
* Remove the crumb at the indicated position and
* all crumbs below and to the right of that position.
* @param cookie cookie from which we want to take a bite
* @param column column of desired bite
* @param row row of desired biete
*/
void takeABite (Cookie& cookie, int column, int row)
{
for (int r = row; r < cookie.numberOfRows; ++r)
{
int c = cookie.crumbs[r];
if (c > column)
cookie.crumbs[r] = column;
}
cookie.numberOfRows = 0;
for (int r = 0; r < cookie.initialNumberOfRows && cookie.crumbs[r] >
0; ++r)
{
cookie.numberOfRows = r + 1;
}
cookie.numberOfColumns = (cookie.numberOfRows > 0) ? cookie.crumbs[0]
: 0;
}
int main (int argc, char** argv)
{
// Start the random number generator
int seed = 12371;
if (argc == 1)
seed = time(0);
srand (seed);
printRules();
bool playAnotherGame = true;
while (playAnotherGame)
{
Game game;
initializeGame(game);
playAGame(game, human, computer);
printScore(human, computer);
cout << "Play again? (Y/N) " << flush;
string response;
playAnotherGame = false;
while (response == "" && cin >> response)
{
if (response[0] == 'Y' || response[0] == 'y' ||
response[0] == 'N' || response[0] == 'n')
playAnotherGame = response[0] == 'Y' || response[0] == 'y';
else
response = "";
}
cleanUpGame(game);
}
return 0;
}
They have to be seperated into a main.cpp, cookie.h, cookie.cpp,
computerPlayer.h, computerPlayer.cpp, humanPlayer.h, humanPlayer.cpp,
player.h, player.cpp, game.h,game.cpp. I am not the best when it comes to
seperation of the .cpp files. I can email anyone if they are able to help
with this is as i know it will be probably easier to see with the specific
file instead of posting it here. Thank you very much everyone!

Language Switcher Typo3

Language Switcher Typo3

I'm trying to create a language switch with personal images that makes
possible to change the website language in the frontend (i already defined
the languages and the alternative language pages). I'm using a snippet
from Typo3 Core Documentation, but it's not working for me, so i must be
doing something wrong...I added a marker in my template called LANGUAGE,
which corresponds to a DIV in the top right corner of the main container,
where would appear some representative flags of the languages available
for that page.
Here it is my TS code in the Template:
config.linkVars = L , type
config.sys_language_uid = 0
config.language = en
config.locale_all = en_EN
[globalVar = GP:L =0]
config.sys_language_uid = 0
config.language = en
config.locale_all = en_EN
config.htmlTag_langKey = en
[global]
[globalVar = GP:L =1]
config.sys_language_uid = 1
config.language = pt
config.locale_all = pt_PT
config.htmlTag_langKey = pt
[global]
[globalVar = GP:L =2]
config.sys_language_uid = 2
config.language = fr
config.locale_all = fr_FR
config.htmlTag_langKey = fr
[global]
[globalVar = GP:L =3]
config.sys_language_uid = 3
config.language = de
config.locale_all = de_DE
config.htmlTag_langKey = de
[global]
page.10.marks.LANGUAGE {
lib.langMenu = HMENU
lib.langMenu {
special = language
special.value = 0,1,2
special.normalWhenNoLanguage = 0
1 = GMENU
1.NO {
XY = [5.w]+4, [5.h]+4
backColor = white
5 = IMAGE
5.file = fileadmin/Template/images/english.png ||
fileadmin/Template/images/portuguese.png ||
fileadmin/Template/images/french.png ||
fileadmin/Template/images/german.png
5.offset = 2,2
}
}
}

Sunday, 15 September 2013

How to I find what is hiding an element?

How to I find what is hiding an element?

I'm having a problem where when the page is loaded, a div element becomes
hidden. Developer Tools in Chrome tells me "element.style" is setting
"display: none"
It's not in my css anywhere to display none. I can't find in either of the
related javascript files anything that would hide the element.
I'm totally lost as to why its hidden.
The jquery plugin I'm using is called Supersized.
Edit: Feel free to check out the page I'm working on:
http://www.gingereventsmpls.com/gallery2.html
If you inspect the html, the element that gets hidden is at the end of
this hierarchy:
body->div"controls-wrapper"->div"controls"->div"tray-button"
tray-button is what is getting display:none attached to it somehow.

Is assuming that another unit test has tested the input of the unit code breaking isolation?

Is assuming that another unit test has tested the input of the unit code
breaking isolation?

I understand that unit tests must be as isolated as possible, i.e. are
self-contained and do not have to rely on outside resources like
databases, network access or even the execution of previous unit tests.
However, suppose I want to test class Y. Class Y uses class X. However, I
have already a number of unit tests that test class X.
I think that in the unit tests of class Y, I could just assume that class
X works properly and use instantiations of it to test class Y
(instantiated in the class Y unit tests, so no leftovers or other
pollution).
Is this correct? Or do I need to mock class X when testing class Y or do
something else entirely? If so or if I should mock class X, what are the
reasons for that?

Trying to stack lines closely in HTML

Trying to stack lines closely in HTML

This should be simple, but I'm not getting it. I'm trying to get three
lines (one small-font, one big, one small) to stack against each other
with single-spacing. Instead, the big-font line always has a double-space
above it (for 48-pt, there's a 48-pt line above it).
I've played with margins, padding, height, borders; I've stripped
everything out but the bare essentials, and I still can't get the top and
middle lines to lie nicely against each other.
Code:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<div style="
font-size:16px;
height:16px;
padding:0px;
border:0px;
margin:0px">
<p>Line 1<p></div>
<div style="
font-size:48px;
height:48px;
padding:0px;
border:0px;
margin:0px">
<p>Line 2</p></div>
<div style="
font-size:16px;
height:16px;
padding:0px;
border:0px;
margin:0px">
<p>Line 3</p></font>
</html>

logout page error session

logout page error session

I'm having a little problem when I try to logout
<?php
session_start();
session_unset();
session_destroy();
header("location:../");
?>
this is my logout code, and that is the error:
Warning: session_start() [function.session-start]: Cannot send session
cache limiter - headers already sent (output started at
/home1/jota/public_html/adm/logout.php:1) in
/home1/jota/public_html/adm/logout.php on line 2
Warning: Cannot modify header information - headers already sent by
(output started at /home1/jota/public_html/adm/logout.php:1) in
/home1/jota/public_html/adm/logout.php on line 6

How to catch the index of immediate greater number in other matrix?

How to catch the index of immediate greater number in other matrix?

Consider example
a=rand(5,1)
b=rand(5,1);
bs=sum(b);
B=b./bs;
cB=cumsum(B)
%OUTPUT
a =
0.7803
0.3897
0.2417
0.4039
0.0965
cB =
0.0495
0.4030
0.7617
0.9776
1.0000
now i want the position of the number in cB which is immediately greater
than the number in a. that is to say i want 5 positions corresponding to
each number in a. So my output should be
P= [4;2;2;3;2]
Please help.

Amazon Widget Firefox Overlap Issue

Amazon Widget Firefox Overlap Issue

I have a wordpress powered website, http://techpatrol.eu
In the sidebar on the right of my site, the Amazon search widget doesn't
display text and images and overlaps the two. I've tried playing around
with various different options and sizes on Amazon, but everytime I use
images they seem to overlap no matter what options I set.
Does anyone know how I might solve this? This only happens in Firefox and
displays fine in Chrome.
Thanks a lot!

Dropdown Box is not populating from MYSQL

Dropdown Box is not populating from MYSQL

I have problem in populating dropdown from mysql in php form. Database
Connection is just fine. But dropdown returns empty. I have two tables.
(id, name, age, etc) and admissions (admissionid, year) Each admission can
have no of students. but each student can have only one admission year. I
am trying this code:
<?php
ob_start();
session_start();
include ('database_connection.php');
$Studentid = $_SESSION['Studentid'];
$sql = "SELECT Admissionid FROM admissions";
$result = mysqli_query($sql);
echo $result;
$dropdown = "<select name='admission_year'>";
while($row = mysqli_fetch_assoc($result)) {
$dropdown .= "\r\n<option
value='{$row['Admissionid']}'>{$row['Admissionid']} </option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>

Saturday, 14 September 2013

Using Parser to send files to program in Netbeans

Using Parser to send files to program in Netbeans

I'm building a simple C++ program for exercise. One of the hints is to
have multiple test cases using test files.
I am told to use parser to "pipe" my txt files to my program. for example,
if i wrote testCase.txt. I would type Parser < testCase.txt.
However, it doesn't seem to work. I know that I can program my software to
read a test file but I was wondering if Parser

wget: reading from a list with id numbers and urls

wget: reading from a list with id numbers and urls

In a .txt file, I have 500 lines containing an id number and a website
homepage URL, in the following way
id_345 http://www.example1.com
id_367 http://www.example2.org
...
id_10452 http://www.example3.net
Using wget and the -i option, I am trying to download recursively part of
these websites, but I would like to store the files in a way that is
linked with the id number (storing the files in a directory called like
the id number, or - the best option, but i think the most difficult to
achieve - storing the html content in a single txt file called like the id
number) . Unfortunataly, the option -i cannot read a file like the one
that i am using. How can link the websites content with their connected
id?
Thanks

WPF Change listview image based on binded value

WPF Change listview image based on binded value

My program connects to a mysql database and then stores data into a
listview. I want to display the rating of the item in the list to be
displayed as a picture not a number. Looking at this response, I figured
out how to display different images using data triggers, but I need a way
to specify a range of numbers. Ex, 0-10 = 0stars.png, 11-50 = 1stars.png,
etc....
Any help would be greatly appreciated.

Is there any alternative to implement javascript`s onClick() function in pure python?

Is there any alternative to implement javascript`s onClick() function in
pure python?

In short: I'm looking is to get the img src value onClick() & pass that
selected image to a pyython function to work with PIL
say, var i = getElementById("image-id").src pass this to python def
whatever(): img = src var from js fun
Is it possible? I know this can be done >>>
def post(self):
val = self.request.get("name_of_the_txt_field_to_get")
self.request.write("val")
but I want the variable to a be an image SRC with a onClick(); button
fucntion, & I want to pass this SRC value to the python function as a
variable.
I'm aware that js is client side & python is server side, So I'm looking
to pass the value to anaother URL say from http://localserver to
http://localserver/image
I've been finding a solution to it & I did came across some
options:https://github.com/atsepkov/RapydScript (but it's a python to
javascript compiler & I'll need to compile it)
another one is the good old http://code.google.com/p/pyv8/ but I can't
figure it out &
this one seems to be pretty interesting PICO & I think would get the job
done, however I can't figure it on how do I run it on GAE
workspace: GAE for python with Jinja2 Template.
Thanks in advance.

jquery html() erases webcontent

jquery html() erases webcontent

On my webpage below some code within the CalcModule.func2() function
writes error messages to a div element with id=errorbox. My problem is
that when I place this div element above the form (myForm), the entire
page is erased when CalcModule.func2() function writes an error message.
Only when I place the div errorbox element below the form (see code) the
page is not erased.
Where do I go wrong?
<head>
<title></title>
<script>
function CalcModule(){};
//some vars
CalcModule.var_a;
CalcModule.var_b;
//etc.
//some functions
CalcModule.func1 = function(msg){
}
CalcModule.func2 = function(){
if(!selected){ //no checkbox selected?
$("#errorbox").removeClass("success");
$("#errorbox").addClass("error");
$("#errorbox").html("errormessage");
}
else{
$("#errorbox").removeClass("error");
$("#errorbox").html("");
}
}
//etc.
$(document).ready(function(){
$("#myForm").validate({})
$.get("process.php", //ajax call
function(msg) {
var form = Getform(msg);
$("#wrapper").append(form);
}
)
}//$(document).ready(function
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<!-- ideally the '<div id="errorbox"><div>' should be at this
location, but that does not work-->
<form id="myForm" name="myForm" action="" method="post"
autocomplete="on">
<!--some table html code here-->
<div id="wrapper"></div> <!--anchor point for adding set of form
fields -->
<input type="submit" name="submitForm" value="Submit Form">
</form>
<div id="errorbox"><div> <!--this seems the only location for this div
on the page where the page is not erased-->
</body>

Pagination, sorting and search function in the same php page

Pagination, sorting and search function in the same php page

I have done the part pagination and sorting function in php. But I have no
idea with the searching function, anyone can help??
Now i am using ajax to pass the searchData to another php page in order to
retrieve data from database. At the beginning the page will show all the
data in , after user have key in any data in searchData, the data in will
change. Although the data have change in but it does not work with
pagination. For exampple, i search for category BOARD,it will be retrieve
from database, but if i click next page,it will return to result at
begining. it means that my pagination function does not work with my
search function. my layout is almost similar to
http://www.ocso.net/offenders/sex-offenders/. the output i wan is same
with this link.
<html>
<head>
<script>
function showResult(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","materialSearch.php?r="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div align="right" id="hsearch">
<input autocomplete="off" name="searchData" id="searchData"
class="textbox" placeholder="search" tabindex="1" type="text"
maxlength="240" size="28" onkeyup="showResult(this.value)"/>
</div>
<div id="txtHint" >
//HERE I HAVE PAGINATION AND SORTING CODE
<?php
$r=$_REQUEST['searchData'];
//DATABASE SETTINGS
$config['host'] = "localhost";
$config['user'] = "root";
$config['pass'] = "";
$config['database'] = "litako";
$config['table'] = "material";
$config['nicefields'] = true; //true or false | "Field Name" or "field_name"
$config['perpage'] = 10;
$config['showpagenumbers'] = true; //true or false
$config['showprevnext'] = true; //true or false
include './Pagination.php';
$Pagination = new Pagination();
//CONNECT
mysql_connect($config['host'], $config['user'], $config['pass']);
mysql_select_db($config['database']);
//get total rows
$totalrows = mysql_fetch_array(mysql_query("SELECT count(*) as total FROM
`".$config['table']."`"));
//limit per page, what is current page, define first record for page
$limit = $config['perpage'];
if(isset($_GET['page']) && is_numeric(trim($_GET['page']))){$page =
mysql_real_escape_string($_GET['page']);}else{$page = 1;}
$startrow = $Pagination->getStartRow($page,$limit);
//create page links
if($config['showpagenumbers'] == true){
$pagination_links =
$Pagination->showPageNumbers($totalrows['total'],$page,$limit);
}else{$pagination_links=null;}
if($config['showprevnext'] == true){
$prev_link = $Pagination->showPrev($totalrows['total'],$page,$limit);
$next_link = $Pagination->showNext($totalrows['total'],$page,$limit);
}else{$prev_link=null;$next_link=null;}
//IF ORDERBY NOT SET, SET DEFAULT
if(!isset($_GET['orderby']) OR trim($_GET['orderby']) == ""){
//GET FIRST FIELD IN TABLE TO BE DEFAULT SORT
$sql = "SELECT material.category,material.product,vendorlist.company FROM
material inner Join vendorlist on material.company=vendorlist.id where
category like '%$r%' LIMIT 1";
$result = mysql_query($sql) or die(mysql_error());
$array = mysql_fetch_assoc($result);
//first field
$i = 0;
foreach($array as $key=>$value){
if($i > 0){break;}else{
$orderby=$key;}
$i++;
}
//default sort
$sort="ASC";
}else{
$orderby=mysql_real_escape_string($_GET['orderby']);
}
//IF SORT NOT SET OR VALID, SET DEFAULT
if(!isset($_GET['sort']) OR ($_GET['sort'] != "ASC" AND $_GET['sort'] !=
"DESC")){
//default sort
$sort="ASC";
}else{
$sort=mysql_real_escape_string($_GET['sort']);
}
//GET DATA
$sql = "SELECT
vendorlist.company,material.id,material.category,material.product,material.description,material.price,material.UOM
FROM material inner Join vendorlist on material.company=vendorlist.id
where category like '%$r%' ORDER BY $orderby $sort LIMIT
$startrow,$limit";
$result = mysql_query($sql) or die(mysql_error());
$sql2 = "SELECT material.category,material.product,vendorlist.company FROM
material inner Join vendorlist on material.company=vendorlist.id ORDER
BY $orderby $sort LIMIT $startrow,$limit";
$result2 = mysql_query($sql2) or die(mysql_error());
//START TABLE AND TABLE HEADER
echo "<table width='100%' >\n<tr>";
$array = mysql_fetch_assoc($result2);
foreach ($array as $key=>$value) {
if($config['nicefields']){
$field = str_replace("_"," ",$key);
$field = ucwords($field);
}
$field = columnSortArrows($key,$field,$orderby,$sort);
echo "<th class='lvtCol'>" . $field . "</th>\n";
}
echo "<th class='lvtCol'>" . "Description of goods" . "</th>\n";
echo "<th class='lvtCol'>" . "Unit Price " . "</th>\n";
echo "<th class='lvtCol'>" . "UOM" . "</th>\n";
echo "<th class='lvtCol'>" . "Action" . "</th>\n";
echo "</tr>\n";
//reset result pointer
mysql_data_seek($result2,0);
//start first row style
$tr_class = "class='odd'";
while($row = mysql_fetch_array($result))
{
$id=$row['id'];
echo "<tr ".$tr_class.">\n";
echo "<td>" . $row['category'] . "</td>";
echo "<td><a href=\"viewMaterial.php?id=$id\" title='click to view'>" .
$row['product']. "</a></td>";
echo "<td>" . $row['company'] . "</td>";
echo "<td width='100'>" . $row['description'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['UOM'] . "</td>";
echo "<td width='5%'>" . "<a href=\"editMaterial.php?id=$id\" title='click
to edit '><img src='edit.gif'/</a>"."|"."<a onclick=\"return
confirm('Are you sure to delete?');\" href=\"deleteMaterial.php? id=$id\"
title='click to delete'><img src='delete.gif'/></a>". "</td>";
echo "</tr>\n";
$num++;
//switch row style
if($tr_class == "class='odd'"){
$tr_class = "class='even'";
}else{
$tr_class = "class='odd'";
}
}
//END TABLE
echo "</table>\n";
if(!($prev_link==null && $next_link==null && $pagination_links==null)){
echo '<div class="pagination">'."\n";
echo $prev_link;
echo $pagination_links;
echo $next_link;
echo '<div style="clear:both;"></div>'."\n";
echo "</div>\n";
}
/*FUNCTIONS*/
function columnSortArrows($field,$text,$currentfield=null,$currentsort=null){
//defaults all field links to SORT ASC
//if field link is current ORDERBY then make arrow and opposite current SORT
$sortquery = "sort=ASC";
$orderquery = "orderby=".$field;
if($currentsort == "ASC"){
$sortquery = "sort=DESC";
$sortarrow = '<img src="arrow_up.png" />';
}
if($currentsort == "DESC"){
$sortquery = "sort=ASC";
$sortarrow = '<img src="arrow_down.png" />';
}
if($currentfield == $field){
$orderquery = "orderby=".$field;
}else{
$sortarrow = null;
}
return '<a href="?'.$orderquery.'&'.$sortquery.'">'.$text.'</a> '.
$sortarrow;
}
?>
</div>
</body>
</html>
Hope can get the solution here. appreciate with your help. Thanks